我有以下课程
ClientDemo.java
ClientTread.java
服务器演示.java
服务器线程.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+"");
}
}
}
SeverDemo.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();
}
}
}
服务器线程.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