关于TCP/IP通信的程序错误
不要用API来糊弄我,我要的是能够解决问题的答案
服务器代码
import java.net.*;
import java.io.*;
public class serverTCP
{
public static void main(String[] args)
{
try{
ServerSocket serversocket=new ServerSocket(2000);
Socket socket=serversocket.accept();
BufferedReader buffer=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String s=buffer.readLine();
System.out.print(s);
socket.close();
}catch(
SocketException e){e.printStackTrace();}
catch(
IOException e1){e1.printStackTrace();}
catch(
UnknownHostException e2){e2.printStackTrace();}
}
}
客户端代码
import java.net.*;
import java.io.*;
public class clientTCP
{
public static void main(String[] args)
{
try{
Socket socket=new Socket(InetAddress.getByName("localhost"),2000);
PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.print("我向你发送了一个连接请求,你收到了吗");
}catch(SocketException e){e.printStackTrace();}
catch(IOException e1){e1.printStackTrace();}
}
}
错误:
当我运行客户端代码时会向服务器端发送一个字符串;
这时服务器端程序出现异常错误:
这是怎么回事,是我没有捕捉异常吗。
我应该怎么修改服务器端的代码:?
不要用API来糊弄我,我要的是能够解决问题的答案
------解决方案--------------------
Java code
import java.net.*;
import java.io.*;
public class serverTCP {
public static void main(String[] args) {
ServerSocket serversocket = null;
Socket socket = null;
BufferedReader buffer = null;
try {
serversocket = new ServerSocket(2000);
socket = serversocket.accept();
buffer = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String s = buffer.readLine();
System.out.print(s);
buffer.close();
socket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
buffer.close();
socket.close();
serversocket.close();
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
}
}