我试图创建一个客户端-服务器应用程序,其中客户端生成一个随机数并向服务器发送 n 个字符串。连接关闭发送字符串“BYE”。之后服务器必须计算接收到的字符串的总长度并打印出来。
问题是,当我的客户端尝试连接到服务器时,此客户端抛出“java.net.SocketException:连接重置”异常并崩溃。
这是我的客户代码:
import java.net.*;
import java.io.*;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ClientStringa {
public static void main(String[] args) {
try{
Socket socket = new Socket("localhost", 5555);
PrintWriter out = new PrintWriter(socket.getOutputStream());
Random r = new Random();
int N = r.nextInt(100);
for(int i=1;i<=N;i++){
out.println("String" +i);
}
out.flush();
}
catch (IOException ex) {
Logger.getLogger(ClientStringa.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
我的服务器代码:
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ServerStringa {
public static void main(String[] args) {
try {
ServerSocket socket = new ServerSocket(5555);
while(true){
System.out.println("Waiting for client connections...");
Socket client = socket.accept(); //connessione dei client
ThreadStringa thread = new ThreadStringa(client);
thread.start();
}
} catch (IOException ex) {
Logger.getLogger(ServerStringa.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
慕哥6287543
相关分类