Java SE实现多人聊天室功能
本文实例为大家分享了JavaSE实现多人聊天室功能的具体代码,供大家参考,具体内容如下
实现功能:
1.实现用户注册上线,下线
2.实现群聊和私聊功能
3.实现统计当前在线人数
实现思路:
1.首先,要实现服务端与客户端之间的连接
这里是使用套接字建立TCP连接:
(1)服务器端先实例化一个描述服务器端口号的ServerSocket对象
(2)客户端要创建Socket对象来连接指定的服务器端
(3)服务器端调用ServerSocket类的accept()方法来监听连接到服务器端的客户端信息
(4)若服务器端与客户端连接成功,双方将返回一个Socket对象,此时双方可以进行通信
(5)服务器端与客户端使用I/O流进行连接,服务端的输出流连接客户端的输入流,客户端的输出流连接服务端的输入流
(6)使用close()方法关闭套接字(一定要记得关闭)
2.因为是拥有一个服务端来实现多个客户端的连接,此处还要解决的是多线程的问题。
每个客户端需要两个线程,来分别处理向服务端发送消息和向服务端接收消息
而服务端,当每增加一个客户端与服务端连接,服务端都要多创建一个线程来处理与客户端的连接
具体代码:
单线程实现:
客户端
importjava.io.IOException;
importjava.io.PrintStream;
importjava.net.Socket;
importjava.util.Scanner;
/**
*@authorLXY
*@email403824215@qq.com
*@date2018/7/2015:46
*/
//客户端
publicclassSingleClient{
publicstaticvoidmain(String[]args)throwsIOException{
//客户端连接服务器,返回套接字Socket对象
Socketsocket=newSocket("127.0.0.1",6666);
//获取服务端的输出流,向服务器端输出内容
PrintStreamprintStream=newPrintStream(socket.getOutputStream());
printStream.println("我是客户端"+socket.getLocalPort());
//获取服务器端的输入流,读取服务器端的内容
Scannerscanner=newScanner(socket.getInputStream());
scanner.useDelimiter("\n");
if(scanner.hasNext())
{
System.out.println(scanner.next());
}
//关闭流
socket.close();
}
}
服务端
importjava.io.IOException;
importjava.io.PrintStream;
importjava.net.ServerSocket;
importjava.net.Socket;
importjava.util.Scanner;
/**
*@authorLXY
*@email403824215@qq.com
*@date2018/7/2015:34
*/
//服务端
publicclassSingleServer{
publicstaticvoidmain(String[]args)throwsIOException{
//创建服务器端的ServerSocket对象,等待客户端进行连接
ServerSocketserverSocket=newServerSocket(6666);
System.out.println("服务器的端口号为6666,等待客户端连接。。。");
//侦听并接收服务器端的连接,返回套接字Socket对象
Socketsocket=serverSocket.accept();
//获取客户端的输入流,读取客户端的输入内容
Scannerscanner=newScanner(socket.getInputStream());
scanner.useDelimiter("\n");
if(scanner.hasNext())
{
System.out.println("客户端发来消息:"+scanner.next());
}
//获取客户端的输出流,向客户端输出内容
PrintStreamprintStream=newPrintStream(socket.getOutputStream());
printStream.println("客户端你好,我是服务器端:"+serverSocket.getLocalPort());
//关闭流
serverSocket.close();
}
}
多线程实现
客户端
importjava.io.IOException;
importjava.io.PrintStream;
importjava.net.Socket;
importjava.util.Scanner;
/**
*@authorLXY
*@email403824215@qq.com
*@date2018/7/2015:55
*/
//客户端
//客户端读取服务器端信息的线程
classClientReadServerimplementsRunnable
{
privateSocketsocket;
publicClientReadServer(Socketsocket)
{
this.socket=socket;
}
publicvoidrun(){
try{
Scannerscanner=newScanner(socket.getInputStream());
while(scanner.hasNext())
{
System.out.println(scanner.next());
}
socket.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
//客户端向服务端发送信息的线程
classClientSendServerimplementsRunnable
{
privateSocketsocket;
publicClientSendServer(Socketsocket)
{
this.socket=socket;
}
publicvoidrun(){
try{
PrintStreamprintStream=newPrintStream(socket.getOutputStream());
Scannerscanner=newScanner(System.in);
while(true)
{
Stringmsg=null;
if(scanner.hasNext())
{
msg=scanner.next();
printStream.println(msg);
}
if(msg.equals("bye"))
{
scanner.close();
printStream.close();
break;
}
}
}catch(IOExceptione){
e.printStackTrace();
}
}
}
publicclassMultiClient{
publicstaticvoidmain(String[]args)throwsIOException{
Socketsocket=newSocket("127.0.0.1",6666);
Threadread=newThread(newClientReadServer(socket));
Threadsend=newThread(newClientSendServer(socket));
read.start();
send.start();
}
}
服务端
importjava.io.IOException;
importjava.io.PrintStream;
importjava.net.ServerSocket;
importjava.net.Socket;
importjava.util.Map;
importjava.util.Scanner;
importjava.util.Set;
importjava.util.concurrent.ConcurrentHashMap;
importjava.util.concurrent.ExecutorService;
importjava.util.concurrent.Executors;
importjava.util.regex.Matcher;
importjava.util.regex.Pattern;
/**
*@authorLXY
*@email403824215@qq.com
*@date2018/7/2016:12
*/
classServerimplementsRunnable
{
privatestaticMapmap=newConcurrentHashMap();
privateSocketsocket;
publicServer(Socketsocket)
{
this.socket=socket;
}
publicvoidrun(){
try{
Scannerscanner=newScanner(socket.getInputStream());
Stringmsg=null;
while(true)
{
if(scanner.hasNextLine())
{
msg=scanner.nextLine();
Patternpattern=Pattern.compile("\r");
Matchermatcher=pattern.matcher(msg);
msg=matcher.replaceAll("");
//用户注册——格式:userName:用户名
if(msg.startsWith("userName:"))
{
StringuserName=msg.split("\\:")[1];
userRegist(userName,socket);
continue;
}
//群聊——格式:G:群聊信息
elseif(msg.startsWith("G:"))
{
firstStep(socket);
Stringstr=msg.split("\\:")[1];
groupChat(socket,str);
continue;
}
elseif(msg.startsWith("P:")&&msg.contains("-"))
{
firstStep(socket);
StringuserName=msg.split("\\:")[1].split("-")[0];
Stringstr=msg.split("\\:")[1].split("-")[1];
privateChat(socket,userName,str);
continue;
}
elseif(msg.contains("bye"))
{
firstStep(socket);
userExit(socket);
continue;
}
else
{
PrintStreamprintStream=newPrintStream(socket.getOutputStream());
printStream.println("格式输入错误");
continue;
}
}
}
}catch(IOExceptione){
e.printStackTrace();
}
}
privatevoidfirstStep(Socketsocket)throwsIOException{
Set>set=map.entrySet();
for(Map.Entryentry:set)
{
if(entry.getValue().equals(socket))
{
if(entry.getValue()==null)
{
PrintStreamprintStream=newPrintStream(socket.getOutputStream());
printStream.println("请先进行注册操作!格式为:[userName:用户名]");
}
}
}
}
privatevoiduserRegist(StringuserName,Socketsocket){
map.put(userName,socket);
System.out.println("用户名:"+userName+"客户端"+socket+"上线了!!");
System.out.println("当前在线人数为"+map.size()+"人");
}
privatevoidgroupChat(Socketsocket,Stringmsg)throwsIOException{
Set>set=map.entrySet();
StringuserName=null;
for(Map.Entryentry:set)
{
if(entry.getValue().equals(socket))
{
userName=entry.getKey();
break;
}
}
for(Map.Entryentry:set)
{
Socketclient=entry.getValue();
PrintStreamprintStream=newPrintStream(client.getOutputStream());
printStream.println(userName+"说"+msg);
}
}
privatevoidprivateChat(Socketsocket,StringuserName,Stringmsg)throwsIOException{
StringcurUser=null;
Set>set=map.entrySet();
for(Map.Entryentry:set)
{
if(entry.getValue().equals(socket))
{
curUser=entry.getKey();
break;
}
}
Socketclient=map.get(userName);
PrintStreamprintStream=newPrintStream(client.getOutputStream());
printStream.println(curUser+"私聊说"+msg);
}
privatevoiduserExit(Socketsocket){
StringuserName=null;
for(Stringkey:map.keySet())
{
if(map.get(key).equals(socket))
{
userName=key;
break;
}
}
map.remove(userName,socket);
System.out.println("用户"+userName+"已下线");
}
}
publicclassMultiServer{
publicstaticvoidmain(String[]args){
try{
ServerSocketserverSocket=newServerSocket(6666);
//使用线程池
ExecutorServiceexecutorService=Executors.newFixedThreadPool(20);
for(inti=0;i<20;i++)
{
System.out.println("欢迎来到聊天室。。。");
Socketsocket=serverSocket.accept();
System.out.println("新人加入。。。");
executorService.execute(newServer(socket));
}
executorService.shutdown();
serverSocket.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。