在Java中使用网络通信实现聊天室私聊和群聊的功能
一、结构图
二、代码实现①服务器类
package com.allen;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 要求实现谁和谁聊天的提示
* @author Administrator
*
*/
public class Server {
//群发
//定义一个集合,用于存储所有客户端的输出流
List<PrintWriter> allPw = new ArrayList<>();
//用于根据用户名存储客户端输出流
Map<String,PrintWriter> map = new HashMap();
//创建线程池对象
//ExecutorService pool = Executors.newCachedThreadPool();
public static void main(String[] args) {
try {
//向系统申请端口号 端口号是系统中所有程序没有使用过的端口,才能使用成功
//端口号的范围:0-65535之间 0-1023之间是系统端口
ServerSocket server = new ServerSocket(8088);
System.out.println("服务端开启成功!!!");
Server s = new Server();
while(true){
System.out.println("等待客户端连接:");
//阻塞方法 accept():等待客户端的连接
Socket accept = server.accept();
System.out.println("和客户端连接成功!!!");
//获取IP地址
InetAddress address = accept.getInetAddress();
String ip = address.getHostAddress();
System.out.println(ip);
Thread t = new Thread(s.new ClientHandler(accept));
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
class ClientHandler implements Runnable{
private Socket socket;
public ClientHandler(Socket socket){
this.socket = socket;
}
public void run(){
try{
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is,"GBK");
BufferedReader br = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os,"GBK");
PrintWriter pw = new PrintWriter(osw,true);
//一个客户端连接服务器,则把输出流存入到集合中
String str = null;
//用户名
String name = br.readLine();
allPw.add(pw);
map.put(name, pw);
while((str = br.readLine())!=null){
if(str.equals("1")){//私聊工作
//需要私聊的对象
str = br.readLine();
//私聊对象的输出流
PrintWriter p = map.get(str);
str = br.readLine();
p.println(str);
}else{//群发
System.out.println("");
str = br.readLine();
for(PrintWriter p:allPw){
if(p == pw){
continue;
}
p.println(str);
}
}
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}
②客户端类
package com.allen;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
//连接服务器
try {
System.out.println("连接服务端");
Socket socket = new Socket("localhost",8088);
System.out.println("连接服务端成功");
Thread t1 = new Thread(new ClientWriteData(socket));
Thread t2 = new Thread(new ClientReadData(socket));
t1.start();
t2.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ClientWriteData implements Runnable{
private Scanner scan;
private Socket socket;
public ClientWriteData(Socket socket){
this.socket = socket;
}
public void run(){
try {
OutputStream out = socket.getOutputStream();
OutputStreamWriter osw;osw = new OutputStreamWriter(out,"GBK");
PrintWriter pw = new PrintWriter(osw,true);
System.out.println("请输入用户名:");
scan = new Scanner(System.in);
String str0 = scan.next();
pw.println(str0);
while(true){
System.out.println("请选择私聊或者群发:1表示私聊\t2表示群发");
int n = scan.nextInt();
pw.println(n);
switch(n){
case 1:
System.out.println("请输入私聊对象: ");
String name = scan.next();
pw.println(name);
System.out.println("私聊的信息:");
String str = scan.next();
pw.println(str);
break;
case 2:
System.out.println("请输入群发消息:");
System.out.println(str0+"正在发消息:");
String str1 = scan.next();
pw.println(str1);
break;
default:
System.out.println("退出消息发送:");
System.exit(0);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ClientReadData implements Runnable{
private Socket socket;
public ClientReadData(Socket socket){
this.socket = socket;
}
public void run(){
try {
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is,"GBK");
BufferedReader br = new BufferedReader(isr);
String str = null;
while((str = br.readLine())!=null){
System.out.println(str);
}
} catch (IOException e) {
System.err.println("服务端已断开!!!");
e.printStackTrace();
}
}
}
三、启动过程 ①首先启动Server类。注意:顺序不能乱。一定要先启动Server类消息队列不能再本地安装的原因,再启动Client类。
②再次启动Client类。如果有多台电脑,可以直接在其他电脑上启动Client类进行连接(当然前提是相关配置如下:端口必须一致)消息队列不能再本地安装的原因,每台电脑的Client都是一个客户端。
③启动Server类和Client类。效果如下图所示
④依次启动相关类成功后,效果图如下:
四、效果展示
由于本次实验需要两台或多台电脑完成实验,鉴于目前博主的条件不满足,具体效果展示留待客官进行实验操作。欢迎在评论区留言讨论。感谢您的支持和理解。
最后,让我们互相学习,共同进步,共同实现目标。