简版的TCP协议聊天

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_38830041/article/details/89418416

客户端

package com.tcp2;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;

/**

         1.客户端
 */
public class 客户端 {
	public static void main(String[] args) {
		//客户端对象
		try(Socket client=new Socket(InetAddress.getByName("localhost"), 9000);
		//用户输入
		  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		//向服务器端发送信息,输出流
		  BufferedWriter  bw=new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
		//读取从服务器写入的内容 输入流
		 BufferedReader bre=new BufferedReader(new InputStreamReader(client.getInputStream()));
		){
			System.out.println("客户端要发送到服务器端的内容为:");
			//通过用户输入信息
			String msg = br.readLine();
			//将用户输入的信息发送到服务器端
			bw.write(msg);
			//换行的标识
			bw.newLine();
			//刷新缓冲区
			bw.flush();
			//等待接收
			String msgServer = bre.readLine();
			System.out.println("从服务器获取的信息:"+msgServer);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}

服务器端:

package com.tcp2;

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

/**

         1.服务器端
 */
public class 服务器端 {
	public static void main(String[] args) {
		//服务器
		try(ServerSocket ss=new ServerSocket(9000);){
			System.out.println("等待客户端的连接。。。。。");
			//连接每一个客户端
			try(Socket client=ss.accept();
				//读取客户端发送的信息
				BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream()));
			    //获取服务器端用户输入的信息
				BufferedReader bin=new BufferedReader(new InputStreamReader(System.in));
			    // 向客户端写入信息
				BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
				){
				//读取客户端发来的信息
				String clientMsg = br.readLine();
				System.out.println("从客户端发来的消息为:"+clientMsg);
				System.out.println("服务器端要发送到客户端的内容为:");
				//服务器端用户输入信息
				String input = bin.readLine();
				//向客户端写入
				bw.write(input);
				bw.newLine();
				bw.flush();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}

展开阅读全文

没有更多推荐了,返回首页