I have a client class that extends Thread to start socket programming
my class code
class MyClientMessages extends Thread {
Socket socket;
int PORT = 5002;
DataInputStream din;
DataOutputStream dout;
public MyClientMessages(String IP) {
try {
System.out.println("IP = ======= " + IP + " TYPE = " + TYPE);
//*********** crash here ***************
socket = new Socket(IP,PORT); // *********** it crash here *************
din = new DataInputStream(socket.getInputStream());
dout = new DataOutputStream(socket.getOutputStream());
this.start();
}catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while (true) {
byte[] data = new byte[1024];
int size = 0;
try {
while ((size = din.read(data)) > 0) {
final String str = new String(data,"UTF8");
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView textView = new TextView(ServerChat.this);
textView.setTextSize(15);
textView.setText(str);
linearLayout.addView(textView);
}
});
}
}catch (IOException e) {
e.printStackTrace();
try {
dout.close();
din.close();
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
public void WriteToSocket(byte[] arr,int size) {
try {
dout.write(arr,0,size);
dout.flush();
}catch (IOException e) {
e.printStackTrace();
try {
dout.close();
din.close();
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
I make this class inside my activity class. I have another class inside my activity class for server, which extends thread and it works fine. Why does this client class crash and give me this error ?
this how I use it on my onCreate() function:
if (TYPE == 1) {
serverMessages = new MyServerMessages(5002);
Toast.makeText(this,"Room Started Wait clients To Join",Toast.LENGTH_LONG).show();
}
else {
clientMessages = new MyClientMessages(deConvert(mycode)); // crash here
Toast.makeText(this,"Connect To Room",Toast.LENGTH_LONG).show();
}
why this client class crash and give me this error ?
Because you are creating a Socket and opening it in the constructor. Move that logic into run().
Related
So my question is when a socket connects is it possible to create two datainputstreams which both reference to 1 socket inputstream. I would like to print out text and text2 but this does not work.
Client code
public static void main(String[] args) {
new Sender();
}
public Sender() {
try {
Socket sock = new Socket("127.0.0.1",1337);
DataOutputStream out = new DataOutputStream(sock.getOutputStream());
out.writeUTF("Test");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Server code
public static void main(String[] args) {
new Listen();
}
public Listen() {
Thread thread = new Thread(this);
thread.start();
}
#Override
public void run() {
try {
ServerSocket serversocket = new ServerSocket(1337);
while(true) {
Socket socket = serversocket.accept();
System.out.println(socket.getPort() + ": " + socket.getInetAddress().getHostAddress());
DataInputStream input = new DataInputStream(socket.getInputStream());
DataInputStream input2 = new DataInputStream(socket.getInputStream());
String text = input.readUTF();
String text2 = input2.readUTF();
if(text != null) {
System.out.println(text);
}
if(text2 != null) {
System.out.println(text2);
}
//socket.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Error");
}
You need a loop, that terminates on EOFException. And don't write code like this. Code that depends on the success of code in a prior try block should be inside that try block.
input = new DataInputStream(socket.getInputStream());
while(!formclosed) {
try {
String addtext = input.readUTF();
addtext = formatText(addtext);
logarea.setText(logarea.getText() + addtext);
} catch (EOFException e) {
System.out.println("Client has disconnected.");
return;
}
}
// any other IOException should be treated as an error
This should run as a background thread, not when you press a button.
I want to send object (custom class) via socket from Client to Server. This is my code:
Server:
private class SocketServerThread extends Thread {
#Override
public void run() {
try {
serverSocket = new ServerSocket(socketServerPORT);
while (true) {
clientSocket = serverSocket.accept();
ObjectInputStream inObject = new ObjectInputStream(
clientSocket.getInputStream());
try {
Te xxx = (Te) inObject.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//DataInputStream dataInputStream = new DataInputStream(
//clientSocket.getInputStream());
//messageFromClient=dataInputStream.readUTF();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//activity.msgFromC.setText(messageFromClient);
}
});
}
}
Client:
public Client(String aIPaddres, int aPort, Te u) {
AddressIP = aIPaddres;
Port = aPort;
sendUser = u;
}
protected Void doInBackground(Void... arg0) {
Socket clientSocket = null;
try {
clientSocket = new Socket(AddressIP, Port);
ObjectOutputStream outObject = new ObjectOutputStream(
clientSocket.getOutputStream());
outObject.writeObject(sendUser);
//DataOutputStream daneWyjsciowe = new DataOutputStream(
//clientSocket.getOutputStream());
//daneWyjsciowe.writeUTF("Czesc!" );
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//response = "IOException: " + e.toString();
} finally {
if (clientSocket != null) {
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
Custom class (Te.class):
public class Te implements Serializable {
public String message;
public Te(String m){
message=m;
}
}
When I passing simple data i.e. String there is no problem. But now I want to pass object, but there is always ClassNotFoundException at server. I read lot of stacks but I didnt find answer. Could U help me?
I just wanna make a Server application which gets Strings and put these into a JTextArea. There are two errors I get, even no errors are showed.
the window can't be closed although I used this statement:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
If the client connects to the Server, the whole window turns black. What could be the error? Here the code:
Client:
public Main() {
super("Main");
setIconImage(Toolkit.getDefaultToolkit().getImage(Main.class.getResource("/images/ic.png")));
panelFields = new JPanel();
panelFields.setLayout(new BoxLayout(panelFields,BoxLayout.X_AXIS));
panelFields2 = new JPanel();
panelFields2.setLayout(new BoxLayout(panelFields2,BoxLayout.X_AXIS));
scrollPane = new JScrollPane();
panelFields.add(scrollPane);
getContentPane().add(panelFields);
getContentPane().add(panelFields2);
getContentPane().setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));
setSize(326, 264);
setVisible(true);
messagesArea = new JTextArea();
scrollPane.setViewportView(messagesArea);
messagesArea.setColumns(30);
messagesArea.setRows(10);
messagesArea.setEditable(false);
startServer = new JButton("Start");
startServer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
socketConnection();
startServer.setEnabled(false);
}
});
panelFields.add(startServer);
}
And the Server connection:
private void socketConnection() {
try {
serverSocket = new ServerSocket(9090);
System.out.println("Listening: " + serverSocket.getLocalPort());
} catch (IOException e) {
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(socket.getInputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Maybe you could tell me, how I can fix those problems and also, how I can make, that the server doesn't close the socket although the client disconnects. I wanna reconnect maybe later...
You need to start your socket listener in its own thread, and you need to add a window close listener that shuts down that thread.
For example:
private ServerSocket serverSocket = null;
private boolean done = false;
private void startServer() {
Thread t = new Thread(new Runnable() {
public void Run() {
socketConnection();
});
}
t.start();
}
private void socketConnection() {
try {
serverSocket = new ServerSocket(9090);
System.out.println("Listening: " + serverSocket.getLocalPort());
while (!done) {
try {
final Socket socket = serverSocket.accept();
Thread t = new Thread(new Runnable() {
public void Run() {
handle(socket);
}
});
t.start();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void handle(Socket socket) {
if (socket == null) return;
try {
dataInputStream = new DataInputStream(socket.getInputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void windowClosing(WindowEvent e) {
done = true;
socketServer.close();
}
Your button click listener should call startServer(), then your window close function would set done = true and call socketServer.close().
Now you have one thread for the UI, one thread for the socket server, and one thread for each connection to the server.
I've made some java code which connects and sends data to my android device over LAN, at the receiver side, the app uses AudioTrack to play the audio.
It seems to be streaming the audio, but the receiver plays back only noise!
Here is my sender code:
MainActivity has the following function -
public void startStream() {
//initiate the audioTrack and play it, then start listening
try {
int minBufferSize = AudioTrack.getMinBufferSize(44100,AudioFormat.CHANNEL_OUT_STEREO,AudioFormat.ENCODING_PCM_16BIT);
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,44100, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STREAM);
audioTrack.play();
Streamer streamer = new Streamer(MainActivity.this);
streamer.execute();
}catch(Exception e) {
say("mainSuperException");
}
}
This is the Streamer class:
public class Streamer extends AsyncTask<Void, Void, Void> {
MainActivity mainActivity = null;
int i = 0;
Streamer(MainActivity m)
{
mainActivity = m;
}
protected Void doInBackground(Void... p) {
try {
byte[] buffer = new byte[1024];
ServerSocket serverSocket = new ServerSocket(3210);
Socket socket = serverSocket.accept();
DataInputStream input = new DataInputStream(socket.getInputStream());
i = 0;
byte[] size = new byte[4];
input.read(size,0,4);
int s = ByteBuffer.wrap(size).getInt();
//Start streaming the file
while (i<s) {
try {
input.read(buffer,0,1024);
++i;
mainActivity.audioTrack.write(buffer, 0, buffer.length);
Log.d("packetTag", "got "+i);
} catch (IOException e) {
e.printStackTrace();
mainActivity.say("InnerioException");
} catch (IllegalStateException e) {
Log.e("packetTag", e.toString());
mainActivity.say("InnerIllegalStateException");
} catch (Exception e) {
Log.e("InnerSuperException", e.toString());
e.printStackTrace();
mainActivity.say("InnerSuperException");
}
}
} catch (IOException io) {
Log.e("ioexception", io.toString());
mainActivity.say("OuterioException");
} catch (Exception e) {
Log.e("SuperException", e.toString());
e.printStackTrace();
mainActivity.say("OuterSuperException");
}
return null;
}
}
And for the sender I used the following Java code:
public class mainClassSend {
public static void main(String[] s)
{
try {
InputStream songInputStream = new FileInputStream("D:\\song.mp3");
byte[] buffer = new byte[1024];
InetAddress group = InetAddress.getByName("192.168.2.8");
Socket socket = new Socket(group,3210);
int i=0;
byte[] size = ByteBuffer.allocate(4).putInt(3359).array();
socket.getOutputStream().write(size);
//Start streaming the file
while ((songInputStream.read(buffer, 0, buffer.length)) > -1) {
try {
socket.getOutputStream().write(buffer, 0, buffer.length);
++i;
System.out.println(i);
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
songInputStream.close();
socket.close();
System.out.println(i);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Right now I'm just desperately trying to get this to work, so I've filled in all the values explicitly, even figured out the exact number of frames it sends, and sent that as the size.
It receives the size correctly, and keeps looping till that value, but all I hear is static.
I've looked all over stackOverflow, and tried looking into a lot of java class documentations, can't seem to figure out whats wrong here.
I have a file with contains my server that get’s content from a client app. How can I send the content the server receives to my MainActvity?
if I try MainActivity main = new MainActivity(); in the server file the app crashes.
Server file.
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
connected_server = true;
} catch (IOException e) {
connected_server = false;
e.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
#Override
public void run() {
if (msg != null){
//Where I need to send the received content to the main activity
Log.e("INPUT", msg);
}
}
}
Main Activity
public class MainActivity extends Activity {
…
public void message_recieve(String msg){
// do stuff with messages
}
}
You need to implement a callback, so that you can receive the result correctly when the server request ends