欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Socket 编程 - 单个客户端

程序员文章站 2022-06-14 16:08:40
...
Socket编程就是根据服务器/客户端模型,在Socket API的基础上开发的网络计算机和进程间相互通信的应用。

1. 服务端绑定一个端口号,并在此端口监听客户端的连接,线程会block直到有客户连接请求,读取请求信息,然后处理并返回。
2. 客户端和指定的服务器的指定端口建立连接,发送请求信息,并等待返回信息。

服务端:
public class MyServer {
	ServerSocket server;
	Socket client;
	BufferedReader in;
	PrintWriter out;
	
	public MyServer() {
		try {
			// Instantiate a ServerSocket with specified port
			server = new ServerSocket(4451);
			
			// Listen on the port to receive the connection request
			client = server.accept();
			
			// Construct a reader to get the information from the client
			in = new BufferedReader(new InputStreamReader(client.getInputStream()));
			
			// Construct a writer to respond to the client
			out = new PrintWriter(client.getOutputStream());
			
			// Continually to retrieve the message from the client
			while (true) {
				String input = in.readLine();
	
				System.out.println(input);
				out.println("has received: " + input);
				out.flush();
				
				if (input.equals("end"))
					break;
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			// Release the resources - omitted
		}
	}

	public static void main(String[] args) {
		new MyServer();
	}
}



客户端:
public class MyClient {
	Socket connection;
	BufferedReader in;
	PrintWriter out;
	BufferedReader reader;
	
	public MyClient() {
		try {
			// Establish a connection to the Socket server
			connection = new Socket(InetAddress.getLocalHost(),4451);
			
			// Construct a reader to get the response from the server
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			
			// Construct a writer to send messages to the server
			out = new PrintWriter(connection.getOutputStream());
			
			// Construct a reader to accept the user input
			reader = new BufferedReader(new InputStreamReader(System.in));
			
			// Continuously send out the messages to the server and receive the response 
			while (true) {
				String str = reader.readLine();
				out.println(str);
				out.flush();
				System.out.println("sent out: " + str);
				
				if (str.equals("end"))
					break;
				
				System.out.println(in.readLine());
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// Release the resources - omitted
		}
	}

	public static void main(String[] args) {
		new MyClient();
	}

}


其中:
1. out = new PrintWriter(connection.getOutputStream()); 使用系统默认的编码格式。
如果默认编码不符合要求,使用OutputStreamWriter指定:
out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "utf-8"));

2. 可以把手动flush改成自动的:
out = new PrintWriter(connection.getOutputStream(), true);
这样,当println, printf, format方法调用时,将缓存输出到底层流并清空缓存。

3. 必须首先开启服务端,否则客户端建立连接的时候会报java.net.ConnectException: Connection refused: connect