Multithreaded Server Receives Data From Just One Client Java
I ve created a simple MultiThreaded server. Everytime it accepts client a DataInputStream and DataOutputStream is created and the comunication start Server: public class Connection
Solution 1:
Cannot reproduce.
Test program, copy-pasted from your edited code and added final
to Socket s
as I am using Java 7, and added client code:
publicclassConnectionimplementsRunnable
{
@Overridepublicvoidrun()
{
try
{
ServerSocketss=newServerSocket(7000);
while (true)
{
System.out.println("Server is listening");
finalSockets= ss.accept();
System.out.println("Client Accepted");
Threadt2=newThread(newRunnable()
{
publicvoidrun()
{
try
{
DataInputStreamdis=newDataInputStream(s.getInputStream());
DataOutputStreamdos=newDataOutputStream(s.getOutputStream());
while (true)
{
Stringtest= dis.readUTF();
dos.writeUTF(test);
System.out.println(test);
dos.flush();
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
s.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
});
t2.start();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
publicstaticvoidmain(String[] args)throws InterruptedException
{
Connectionc=newConnection();
Threadt1=newThread(c);
t1.setDaemon(true);
t1.start();
Runnabler=newRunnable()
{
publicvoidrun()
{
try (Sockets=newSocket("localhost", 7000))
{
DataOutputStreamdos=newDataOutputStream(s.getOutputStream());
DataInputStreamdis=newDataInputStream(s.getInputStream());
for (inti=0; i < 10; i++)
{
dos.writeUTF("Hello from "+Thread.currentThread().getName());
Stringreply= dis.readUTF();
Thread.sleep(10*1000);
}
}
catch (IOException|InterruptedException exc)
{
exc.printStackTrace();
}
}
};
Threadt2=newThread(r);
Threadt3=newThread(r);
t2.start();
t3.start();
t2.join();
t3.join();
}
}
Output:
Server is listening
Client Accepted
Server is listening
Client Accepted
Server is listening
Hello from Thread-1
Hello from Thread-2
Hello from Thread-2
Hello from Thread-1
Hello from Thread-2
Hello from Thread-1
Hello from Thread-2
Hello from Thread-1
Hello from Thread-1
Hello from Thread-2
Hello from Thread-1
Hello from Thread-2
Hello from Thread-2
Hello from Thread-1
Hello from Thread-1
Hello from Thread-2
Hello from Thread-2
Hello from Thread-1
Hello from Thread-2
Hello from Thread-1
Post a Comment for "Multithreaded Server Receives Data From Just One Client Java"