我最近在 java 中编写了一个套接字通信程序,其中两个线程在每个服务器和客户端并发运行,处理对套接字的读写操作,允许双方连续发送和接收消息。
问题是客户端或服务器停止接收来自另一端的通信,然后一段时间后它们都停止工作。我不知道出了什么问题以及连接如何断开:/
服务器代码
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class Server
{
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
private DataOutputStream out = null;
private Scanner inp = null;
String line = "";
String iline = "";
public Server(int port)
{
try
{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socket
out=new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(new
BufferedInputStream(socket.getInputStream()));
inp = new Scanner(System.in);
while (true)
{
new Thread(new Runnable(){
public void run()
{
try{
while(true){
line = in.readUTF();
System.out.println("Client : "+line);
if(socket.isClosed()||socket.isOutputShutdown()||socket.isInputShutdown())
{
System.out.println("DED");
System.exit(0);
}
}
}
catch(Exception e){
System.out.println("Exception !!!");
}
}
})
慕的地6264312
相关分类