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

基于TCP/IP的网络聊天室实现(简单一对一)

程序员文章站 2022-03-10 17:21:14
/** * 服务端 * @author mrchai * */public class Server {public static void main(String[] args) throws IOException {//在2345端口创建服务ServerSocket server = new ServerSocket(2345);System.out.println("服务器已启动..."); //开启服务等待客户端连接Socket s = server....

基于TCP/IP的网络聊天室实现(简单一对一)

/**
 * 服务端
 * @author mrchai
 *
 */
public class Server {

	public static void main(String[] args) throws IOException {
		//在2345端口创建服务
		ServerSocket server = new ServerSocket(2345);
		System.out.println("服务器已启动..."); 
		//开启服务等待客户端连接
		Socket s = server.accept();
		System.out.println("客户端连接:"+s.getInetAddress().getHostAddress()); 
		//获取基于Socket的输出流并包装为打印流
		MsgUtils.sendMsg(s.getOutputStream(),"来啦,老弟!!!");
		//获取标准输入流文本扫描对象
		Scanner sc = new Scanner(System.in);
		//开启循环通信
		while(true) {
			//接收消息
			String msg = MsgUtils.readLine(s.getInputStream());
			System.out.println("client:"+msg);
			
			//发送消息
			msg = sc.nextLine();
			MsgUtils.sendMsg(s.getOutputStream(), msg); 
		}
	}
}

/**
 * 客户端
 * @author mrchai
 *
 */
public class Client {

	public static void main(String[] args) throws UnknownHostException, IOException {
		//连接到指定地址指定端口的服务
		Socket s = new Socket("192.168.7.141",2345);
		//获取标准输入流文本扫描对象
		Scanner sc = new Scanner(System.in);
		//开启循环通信
		while(true) {
			//接收消息
			String msg = MsgUtils.readLine(s.getInputStream());
			System.out.println("server:"+msg);
			
			//发送消息
			msg = sc.nextLine();
			MsgUtils.sendMsg(s.getOutputStream(), msg); 
		}
	}
}
/**
 * 消息工具类
 * 包含对消息的读入以及写出相关操作
 * @author mrchai
 */
public class MsgUtils {

	/**
	 * 将字节流以一行文本返回
	 * @param is
	 * @return
	 * @throws IOException 
	 */
	public static String readLine(InputStream is) throws IOException {	

			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);				
			String msg = br.readLine();
			return msg;
	
	}
	
	/**
	 * 通过输出流发送文本消息
	 * @param os
	 * @param msg
	 */
	public static void sendMsg(OutputStream os,String msg) {
		PrintWriter pw = new PrintWriter(os);
		pw.println(msg);
		pw.flush();
	}
}

本文地址:https://blog.csdn.net/YY2748/article/details/107600084

相关标签: java 网络