码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA基础-聊天室小项目

时间:2020-07-03 21:41:22      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:输入   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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!