当前位置: 移动技术网 > IT编程>软件设计>设计模式 > 基于TCP/IP的网络聊天室实现(简单一对一)

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

2020年07月27日  | 移动技术网IT编程  | 我要评论

一个发送另一个接收,每次只能发1行内容

/**
 * 服务端
 * @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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网