I am creating a Chat in java. I have a method (onMouseRelease) inside an object that creates a tcp server and waits for a socket like this:
ServerSocket server = new ServerSocket(port);
Socket channel = server.accept();
Now I want to make a thread that will loop and read data from the socket, so that once the user on the other side sends me a string, I will extract the data from the socket (or is it called packet? Sorry, I am new to this) and update a textbox to add the additional string from the socket (or packet?).
I have no idea how to READ (extract) the information from the socket(/packet) and then update it into a JTextArea which is called userOutput. And how to send a string to the other client, so that it will also could read the new data and update its JTextArea. From what I know, for a 2 sided TCP communication you need one computer to host a server and the other to connect (as a client) and once the connection is set the client can also receive new information from the socket. Is that true? and please tell me how.
Any help is appreciated! I know this is a bit long but I have searched a lot and didn't understand it (I saw something like P开发者_如何学GorintWriter but failed to understand).
You would have to do something like this;
InputStream in = new BufferedInputStream(channel.getInputStream());
You can then read characters from the socket using a loop;
char ch;
while (!finished) {
ch = in.read(); //read from socket
if(ch = -1) {
//nothing left to read
finished = true;
}
else {
//do something with ch
}
}
I can continue if you'd like?
Say we saved the incoming chars to a String called input, to update your text area you would call;
textArea.setText(input);
And to send text back to the client you would use a similar method to receiving, using an outputstream;
OutputStream out = new BufferedOutputStream(clientSock.getOutputStream());
out.write(output);
精彩评论