Socket编程(二)随时接收客户端消息及多客户端连接

使服务器具有随时接收消息的能力

使用类似于心跳包的方法进行测试


SocketClient

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class SocketClient {

	public static void main(String[] args) {
		SocketClient client = new SocketClient();
		client.start();
	}
	
	public void start() {
		BufferedReader inputReader = null;
		// 从socket读取
		BufferedReader reader = null;
		BufferedWriter writer = null;
		Socket socket = null;
		// Alt + Shift + z    try...catch等快捷键
		// 从Console读取内容
		try {
			socket = new Socket("127.0.0.1", 9898);
			// 用于读取服务器返回的数据
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			// 从socket进行写入
			writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			inputReader = new BufferedReader(new InputStreamReader(System.in));
			startServerReplyListener(reader);
			String inputContent;
			while (!(inputContent = inputReader.readLine()).equals("bye")) {
				writer.write(inputContent + "\n");
				writer.flush();
//				System.out.println(inputContent);
//				// 服务器返回的数据
//				String response = reader.readLine();
//				System.out.println(response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				reader.close();
				writer.close();
				inputReader.close();
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 接收服务器消息的监听器
	 * 需要一直运行
	 */
	public void startServerReplyListener(final BufferedReader reader) {
		new Thread(new Runnable() {
			public void run() {
				try {
					String response;
					while ((response = reader.readLine()) != null) {
						System.out.println(response);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

}

SocketServer

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;

public class SocketServer {
	
	BufferedWriter writer;

	public static void main(String[] args) {
		SocketServer socketServer = new SocketServer();
		socketServer.startServer();
	}
	
	public void startServer() {
		ServerSocket serverSocket = null;
		BufferedReader reader = null;
		Socket socket = null;
		try {
			// 端口号只要不冲突就行
			serverSocket = new ServerSocket(9898);
			System.out.println("server started..");
			// 进入阻塞状态,等待客户端接入
			socket = serverSocket.accept();
			System.out.println("client " + socket.hashCode() + " connected");
			// 从socket中读取数据
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			/*
			 * 首次发送延迟3s
			 * 每次心跳时间间隔为3s
			 */
			new Timer().schedule(new TimerTask() {
				public void run() {
					try {
						System.out.println("heart beat once..");
						writer.write("heart beat once..\n"); // 记得加换行符(\n),否则会不被认为已经结束
						writer.flush();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}, 3000, 3000);
			String receiveMsg;
			while ((receiveMsg = reader.readLine()) != null) { // 以"\n"结束
				System.out.println(receiveMsg);
				writer.write("server reply:" + receiveMsg + "\n");
				writer.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				reader.close();
				writer.close();
				socket.close();
				serverSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}


和多个客户端建立通信的功能

SocketServer

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer {
	
	BufferedWriter writer;
	
	BufferedReader reader;

	public static void main(String[] args) {
		SocketServer socketServer = new SocketServer();
		socketServer.startServer();
	}
	
	public void startServer() {
		ServerSocket serverSocket = null;
		Socket socket = null;
		try {
			// 端口号只要不冲突就行
			serverSocket = new ServerSocket(9898);
			System.out.println("server started..");
			while (true) {
				// 进入阻塞状态,等待客户端接入
				socket = serverSocket.accept();
				manageConnection(socket);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				socket.close();
				serverSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void manageConnection(final Socket socket) {
		new Thread(new Runnable() {
			public void run() {
				try {
					System.out.println("client " + socket.hashCode() + " connected");
					// 从socket中读取数据
					reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
					writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
					String receiveMsg;
					while ((receiveMsg = reader.readLine()) != null) { // 以"\n"结束
						System.out.println("client " + socket.hashCode() + ":" + receiveMsg);
						writer.write("server reply:" + receiveMsg + "\n");
						writer.flush();
					}
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						reader.close();
						writer.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

}





你可能感兴趣的:(Socket)