'Socket sending work only the first time and after it throw an SocketException
Here's my client code:
public static void main(final String[] args)
{
try (final Scanner scanner = new Scanner(System.in))
{
System.out.println("Type:");
try (final Socket socket = new Socket("127.0.0.1", 80);
final DataOutputStream dout = new DataOutputStream(socket.getOutputStream()))
{
while (scanner.hasNext())
{
dout.writeUTF(scanner.nextLine());
dout.flush();
}
}
}
catch (final Exception e)
{
e.printStackTrace();
}
and here's my server:
public ConnectorData()
{
try
{
_server = new ServerSocket(80);
}
catch (final Exception e)
{
e.printStackTrace();
}
while (true)
{
try
{
try (final Socket socket = _server.accept();
final DataInputStream dis = new DataInputStream(socket.getInputStream()))
{
System.out.println(dis.readUTF());
}
}
catch (final Exception e)
{
e.printStackTrace();
}
}
}
it works fine in the first message but when i type again in console and hit enter it freezes and then i send again third time and it throw me an:
java SocketException: An established connection was aborted by the software in your host machine
What is it for? Where is my mistake? I basically want to type in chat anything i want and when i press enter to send in server and print it out on console.
Solution 1:[1]
Compare and contrast:
Your client creates a
Socketconnected to your server, then sends a bunch ofStrings through it.Your server accepts a connection from a client to establish a
Socket, reads oneStringfrom it, and then goes back to repeat the whole process.
It is not surprising, then, that the first line you type at the client is transferred successfully, but subsequent ones are not. The server's behavior needs to match the client: it needs to keep reading data from the same socket until the client is done sending. If you want it to afterward loop back to try to accept another connection then that's a separate matter.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | John Bollinger |
