私は次のクラスを持っています
ClientDemo.java
ClientTread.java
ServerDemo.java
ServerThread.java
public class ClientDemo {
public static void main(String[] args) throws InterruptedException {
try {
Socket client=new Socket("localhost", 6666);
while(true)
{
System.out.println("Hello");
Thread th=new Thread(new ClientThread(client));
th.start();
System.out.println("Thread started........");
th.sleep(1000*30);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ClientThread.java
public class ClientThread implements Runnable {
Socket c;
public ClientThread(Socket client) {
this.c=client;
}
@Override
public void run() {
DataOutputStream dos=null;
try {
System.out.println("Client thread is going to write.......");
dos = new DataOutputStream(c.getOutputStream());
dos.writeUTF("Hello From Client");
System.out.println("Data written by client............");
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println(e+"");
}
}
}
ServerDemo.java
public class ServerDemo {
public static void main(String[] args) {
try {
ServerSocket serversocket=new ServerSocket(6666);
System.out.println("server listening..........");
Thread ts=new Thread( new ServerThread(serversocket.accept()));
ts.start();
System.out.println("server thread started.........");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ServerThread.java
public class ServerThread implements Runnable {
Socket s;
public ServerThread(Socket server) {
this.s=server;
}
@Override
public void run() {
DataInputStream dis;
try {
dis = new DataInputStream(s.getInputStream());
String message=dis.readUTF();
System.out.println(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
コードは一度完全に実行されますが、その後、次のエラーが発生します
クライアント コンソールで
Hello
Thread started........
Client thread is going to write.......
Data written by client............
Hello
Thread started........
Client thread is going to write.......
java.net.SocketException: Connection reset by peer: socket write error