JAVA基础-聊天室小项目

2021-04-29 09:28

阅读:654

标签:输入   put   err   his   soc   generated   bre   cat   信息   

package Task;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.util.Scanner;

public class ServerTask implements Runnable{

Socket socket;


//实现绑定
public ServerTask(Socket socket) {
	// TODO Auto-generated constructor stub
	this.socket = socket;
}

@Override
public void run() {
	// TODO Auto-generated method stub
	System.out.println(  socket.getRemoteSocketAddress()+"进入了聊天室!" );
	//输入流
	try {
		
		//字节流-》字符流-》缓冲流
		BufferedReader bReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		
		/**
		 * 客户端信息不为空,那么服务器端可以回应
		 */
		String msg = bReader.readLine();
		while ( msg != null) {
			System.out.println(socket.getRemoteSocketAddress() + "说:" + msg);
			
			
			//服务器端回应
			//字节流转字符流
			PrintWriter pWriter = new PrintWriter(socket.getOutputStream(),true );
			Scanner scanner = new Scanner(System.in);
			pWriter.println("服务器对"+socket.getRemoteSocketAddress()+"说:"+scanner.nextLine());
			
			msg = bReader.readLine();
		}
	}catch (SocketException e) {
		System.out.println(  socket.getRemoteSocketAddress() + "退出聊天室" );
	}catch (Exception e) {
		// TODO: handle exception
	}
}

}

JAVA基础-聊天室小项目

标签:输入   put   err   his   soc   generated   bre   cat   信息   

原文地址:https://www.cnblogs.com/JeasonIsCoding/p/13232574.html


评论


亲,登录后才可以留言!