Socket实现客户端和服务端

客户端

public class Client {
	public static void main(String[] args) {
		// 服务端地址和端口
		final String DEFAULT_SERVER_HOST = "127.0.0.1";
		final Integer DEFAULT_SERVER_PORT = 8888;
		Socket socket = null;
		try {
			// 创建socket
			socket = new Socket(DEFAULT_SERVER_HOST, DEFAULT_SERVER_PORT);
			// 接收消息
			BufferedReader buffReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			// 发送消息
			BufferedWriter buffWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			String msg = null;
			// 获取用户输入的消息
			BufferedReader userReader = new BufferedReader(new InputStreamReader(System.in));
			while (true) {
				String input = userReader.readLine();
				// 写入客户端要发送的消息。因为服务端用readLine获取消息,其以\n为终点,所以要在消息最后加上\n
				buffWriter.write(input + "\n");
				// 刷新缓存
				buffWriter.flush();
				// 读取服务端信息
				msg = buffReader.readLine();
				System.out.println(msg);
				// 如果客户端输入quit就可以跳出循环、断开连接了
				if (input.equals("quit")) {
					break;
				}
			}
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

服务端

public class Server {
	public static void main(String[] args) {
		// 监听8888端口
		final int DEFAULT_PORT = 8888;
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket(DEFAULT_PORT);
			while (true) {
				// 阻塞监听
				Socket socket = serverSocket.accept();
				System.out.println("Client[" + socket.getPort() + "]Online");
				// 读取消息
				BufferedReader buffReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				// 发送消息
				BufferedWriter buffWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
				String msg = null;
				while ((msg = buffReader.readLine()) != null) {
					System.out.println("Client[" + socket.getPort() + "]:" + msg);
					// 写入服务端要发送的消息
					buffWriter.write("Server:" + msg + "\n");
					buffWriter.flush();
					if (msg.equals("quit")) {
						System.out.println("Client[" + socket.getPort() + "]:Offline");
						break;
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值