gpt4 book ai didi

客户端关闭连接后Java TCPSocket中断

转载 作者:可可西里 更新时间:2023-11-01 02:51:49 25 4
gpt4 key购买 nike

<分区>

我对编程很陌生,尤其是套接字编程。我试图弄清楚通信实际上是如何工作的(不是在我所有的书中),但立即遇到了我下载的 SimpleEchoServer 示例的第一个问题。 Communicationflow 工作但是当 Clientsocket 关闭他的连接而不发送特定的字符串时,我的 serversocket 崩溃了。你能告诉我我做错了什么吗?

这是服务器端:

import java.net.*; 
import java.io.*;
import java.net.InetAddress;

public class EchoServer {

public static void main(String[] args) throws IOException {

ServerSocket serverSocket = null;
Integer port = new Integer(args[0]);

try {

serverSocket = new ServerSocket(port);

}

catch (IOException e) {

System.err.println("Could not listen on port: "+port);
System.exit(1);

}

Socket clientSocket = null;
System.out.println ("Waiting for connection on port "+port+" ...");

try {

clientSocket = serverSocket.accept();

}

catch (IOException e) {

System.err.println("Accept failed.");
System.exit(1);

}

System.out.println ("Connection successful");
System.out.println ("Waiting for input.....");

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8"));

String inputLine;

while ((inputLine = in.readLine()) != null) {

System.out.println ("received: " + inputLine);
out.println(inputLine);

if (inputLine.equals("Bye."))
break;

}

out.close();
in.close();
clientSocket.close();
serverSocket.close();

}

}

那是客户端

import java.io.*;
import java.net.*;

public class EchoClient {

public static void main(String[] args) throws IOException {

String serverHostname = new String (args[0]);
Integer port = new Integer(args[1]);

if (args.length > 0)

serverHostname = args[0];
System.out.println ("Attemping to connect to host " + serverHostname + " on port 10007.");

Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;

try {

echoSocket = new Socket(serverHostname, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream(), "UTF-8"));

} catch (UnknownHostException e) {

System.err.println("Don't know about host: " + serverHostname);
System.exit(1);

} catch (IOException e) {

System.err.println("Couldn't get I/O for " + "the connection to: " + serverHostname);
System.exit(1);

}

BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;

System.out.print ("input: ");

while ((userInput = stdIn.readLine()) != null) {

out.println(userInput);
System.out.println("echo: " + in.readLine());
System.out.print ("input: ");

}

out.close();
in.close();
stdIn.close();
echoSocket.close();

}

}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com