使用ServerSocket和Socket出现Connection reset的解决办法

服务器端代码:

package Socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server{
	public static void main(String[] args) {
		try {
			ServerSocket serverSocket = new ServerSocket(9999);
			Socket socket = serverSocket.accept();
			InputStream in = socket.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			System.out.println("未收到信息");
			String line = br.readLine();
			System.out.println(line);
			System.out.println("收到信息");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
 客户端代码:
package Socket;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;


public class client {
	public static void main(String[] args) {
		try {
			Socket socket = new Socket("127.0.0.1", 9999);
			OutputStream os = socket.getOutputStream();
			PrintStream ps = new PrintStream(os);
			ps.print("服务器,你好");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
 
  
解决办法:在客户端关闭流(os.close())
修改后客户端的代码如下:
package Socket;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;


public class client {
	public static void main(String[] args) {
		try {
			Socket socket = new Socket("127.0.0.1", 9999);
			OutputStream os = socket.getOutputStream();
			PrintStream ps = new PrintStream(os);
			ps.print("服务器,你好");
			os.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


 
  

 
  
 

你可能感兴趣的:(java)