Skip to main content

socket exception

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
No replies
voipp
Offline
Joined: 2013-10-17

Hi ! I try to write a simple chat, but exception occures. That is my code :

Server that i run first :

public class WServer {
public static void main(String[] args) throws IOException
{
int port=6666;
ServerSocket ss = new ServerSocket(port);
while(true)
{
Socket s = ss.accept();
new ClientThread(s);
}
}
}

Thread that connects with a client and send back messages :

public class ClientThread implements Runnable {

private Socket s=null;
public ClientThread(Socket s)
{
this.s = s;
Thread t = (new Thread(this,"thread_from_".concat(s.getInetAddress().getHostName())));
t.setDaemon(true);
t.run();
}
@Override
public void run() {
try {
if(s.isClosed())return;

//поток входных данных от клиента
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
//поток выходных данных к клиенту
PrintWriter dos = new PrintWriter( new BufferedOutputStream(s.getOutputStream()));
while(s.isConnected())
{

String c;
c = br.readLine();
dos.println(c);
}
}
And finally client that send messages to ClientThread :

public class Client implements Runnable{

private static Client cl;
public static void main(String[] args) throws IOException, InterruptedException
{

cl = new Client();
Thread t = (new Thread(cl) );
t.start();
t.join();
}
@SuppressWarnings("deprecation")
@Override
public void run() {
String adress = "127.0.0.1";
Socket s;
try {
s = new Socket(InetAddress.getByName(adress) , 6666);

BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));

//поток выходных данных к клиенту
PrintWriter dos = new PrintWriter( new BufferedOutputStream(s.getOutputStream()));

//поток чтения пользовательского ввода
BufferedReader br1 = new BufferedReader( new InputStreamReader( (System.in) ) );

String cstr;
try {

System.out.print("Client: ");
cstr = br1.readLine();
System.out.print("\n");

//отправляем севреру строки, пока не втсретим символ z
while(cstr.equalsIgnoreCase("z"))
{

dos.write(cstr);
System.out.println( "Server: ".concat( br1.readLine() ));
System.out.print("Client: ");
cstr = br1.readLine();
System.out.print("\n");
}

}

After sending message from Client , in the c = br.readLine(); code (from ClientThread) i receive an exception :

java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)

I need your help