【Socket 通信编程】【TCP双向通信多线程】

/* 服务器端,引入多线程 */
import java.io.*;
import java.net.*;
class ServerThread extends Thread {
	private Socket socket = null;
	private int no;
	public ServerThread (Socket socket, int no) {
		this.socket = socket;
		this.no = no;
	}
	@Override
	public void run() {
		String line = null;
		InputStream input = null;
		OutputStream output = null;
		BufferedReader bf = null;
		PrintWriter out = null;
		try {
			// 向客户端发送消息
			output = socket.getOutputStream();
			input = socket.getInputStream();
			bf = new BufferedReader(new InputStreamReader(input));
			out = new PrintWriter(output);
			while((line=bf.readLine())!=null) {
				System.out.println("来自客户端" + no + "的消息: " + line);
				// 向客户端发送确认消息
				out.println(line);
				out.flush();
			}
		} catch (IOException e) {
			// e.printStackTrace();
			System.out.println("客户端" + no + "已断开与服务器的连接");
		} finally {
			try {
				if (input != null)
				    input.close();
				if (output != null)
					output.close();
				if (bf != null)
					bf.close();
				if (out != null)
					out.close();
				if (socket != null)
					socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}	
		}
	}
}
public class MultiThreadServer {
	static int port = 2019;
	 public static void main(String[] args) throws Exception {
		ServerSocket listenSocket = new ServerSocket(port);
        Socket socket = null;
        int count = 0;
        System.out.println("服务器正在监听端口号<" + port + ">");		
        while(true){
            socket = listenSocket.accept();
			count++;
			System.out.println("已连接到客户端" + count + "...");
            ServerThread serverThread = new ServerThread(socket, count);
            serverThread.start();
        }
    }
}

/* 客户端 */
import java.net.*;
import java.io.*;
public class Client {
	// 定义端口和IP地址
	static int port = 2019; 
	static String IP = "127.0.0.1"; 
	public static void main(String args[]) throws Exception {
		// 定义客户端输入和服务器响应
		String userInput = null; 
		String echoMessage = null;
		
		// 将键盘输入读入缓冲区stdIn
		BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
		// 定义客户端套接字
		Socket socket = new Socket(IP, port);
		System.out.println("已连接到服务器...");
		
		// 客户端套接字上的getInputStream方法得到的输入流是从服务器端发回的数据
		InputStream inStream = socket.getInputStream();
		// 客户端套接字上的getOutputStream方法得到的输出流是发给服务器端的数据
		OutputStream outStream = socket.getOutputStream();
		
		// 将服务器端发回的数据读入缓冲区in
		BufferedReader in = new BufferedReader(new InputStreamReader(inStream));
		// 定义向服务器发送数据流的对象out
		PrintWriter out = new PrintWriter(outStream);
		while((userInput = stdIn.readLine())!=null) {
			// 向服务器打印数据
            out.println(userInput);
			// flush方法的作用是刷新缓冲区
			out.flush();
			echoMessage = in.readLine();
			System.out.println("服务器已收到消息: " + echoMessage);
		}
		socket.close();
	}
}

测试结果

【Socket 通信编程】【TCP双向通信多线程】

【Socket 通信编程】【TCP双向通信多线程】

BY DXH924

2019.4.14