#Localhost Console identity.
1 messages · Page 1 of 1 (latest)
Can you share what you have so far - and indicate where you open the sockets.
- Your client should be reusing the same socket.
- Sockets should be closed once you've finished with them.
- If you're going to use Scanner to get input, you want to reuse the scanner too.
- Scanners that consume
System.inshould not be closed.
To reuse the socket you need to restructure things...
- A method to make the connection returning the socket (or a wrapper that contains the socket)
- Methods to send/receive messages taking the socket and scanner (though I'd also separate the sending of the message from the getting of the message from the user).
Close it after you've finished the chat, not every message.
What does the server code look like?
Ahh I see your sendMessage, while having port and address doesn't actually use them.
So your calling code could be improved, but does look like it's reusing the socket (and socket is in fact never properly closed).
So what does the server code look like...
So you accept new connections in a loop. The loop receives one message from the client, closes it, and then loops again to get a new connection.
Each client could be sending more messages - for that you need to either receive them concurrently (threads) or poll them (keep them in a collection and then check each to see if they have any more messages, removing any closed connections from the collection).
So it's unsurprising that each message has a different connection, because it's a different connection.
The server offers a port to connect to (the serversocket). Each connected clientsocket is given a port (they can't all use the same port for their connection to the server)
A common beginners implementation is creating a 'handler' thread that takes the socket and processes it's input/output until the socket is closed.
There are two common socket protocols... TCP and UDP... TCP is connection-based (and has reliability mechanisms), UDP is connectionless.
The model you're using is TCP (connection based)
I don't have any handy.
The clientside of yours could be simplified to be something like...
try (Socket socket = new Socket(server, port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) {
System.out.println("Enter a message (type 'bye' to quit):");
while (true) {
String message = System.console().readln("-");
out.println(message);
if (message.equals("bye")) {
break;
}
}
} catch (IOException e) {
// socket errors
}
This uses try-with-resources to close the socket when done, and the System console for the user input. It creates the PrintWriter once for the socket.