客户端代码:
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
class ReadFromServer implements Runnable{
private Socket client;
public ReadFromServer(Socket client) {
this.client = client;
}
@Override
public void run() {
Scanner readFromServer = null;
try {
readFromServer = new Scanner(client.getInputStream());
readFromServer.useDelimiter("\n");
while (true){
if(readFromServer.hasNextInt()){
String str = readFromServer.nextLine();
System.out.println("服务器说:"+str);
}
if(client.isClosed()){
System.out.println("客户端已经关闭");
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
readFromServer.close();
}
}
}
class SendMsgToServer implements Runnable{
private Socket client;
public SendMsgToServer(Socket client) {
this.client = client;
}
@Override
public void run() {
Scanner in = new Scanner(System.in);
in.useDelimiter("\n");
PrintStream sendMsgToServer = null;
try {
sendMsgToServer = new PrintStream(client.getOutputStream(),true,"UTF-8");
while (true){
System.out.println("请输入要发送的信息:");
if(in.hasNextLine()){
String strToServer = in.nextLine().trim();
sendMsgToServer.println(strToServer);
if(strToServer.contains("byebye")){
System.out.println("关闭客户端");
break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
sendMsgToServer.close();
in.close();
}
}
}
}
public class MutiThreadClient {
public static void main(String[] args) throws IOException {
Socket client = new Socket("127.0.0.1", 6666);
Thread readthread = new Thread(new ReadFromServer(client));
Thread sendthread = new Thread(new SendMsgToServer(client));
readthread.start();
sendthread.start();
}
}
服务器端代码:
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collection;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MutiThreadServerSocket {
//使用ConcurrentHashMap,存在线程安全问题
private static Map<String,Socket> clientsMap = new ConcurrentHashMap<>();
private static class ExectueClientRequest implements Runnable{
private Socket client;
public ExectueClientRequest(Socket client) {
this.client = client;
}
@Override
public void run() {
Scanner readFromClient =null;
try {
readFromClient = new Scanner(client.getInputStream());
readFromClient.useDelimiter("\n");
while (true){
if(readFromClient.hasNextLine()){
String str = readFromClient.nextLine();
/**
* 用户注册:userName
* 群聊实现:G:
* 私聊实现:P:zhangsan -
*/
//进行\r过滤 --正则方法
Pattern pattern = Pattern.compile("\r");
Matcher matcher = pattern.matcher(str);
str = matcher.replaceAll("");
if (str.startsWith("userName")){
String userName = str.split(":")[1];
userRegister(userName,client);
continue;
}
if(str.startsWith("G:")){
String msg = str.split(":")[1];
GroupChat(msg);
continue;
}
if (str.startsWith("P:")){
String msg = str.split(":")[1];
String username = msg.split("-")[0];
String privatemsg = msg.split("-")[1];
privateChat(username, privatemsg);
continue;
}
if (str.contains("byebye")){
String userName = str.split(":")[0];
userExist(userName);
continue;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 用户注册方法
*/
private void userRegister(String userName, Socket client){
//将用户信息保存到服务器中
clientsMap.put(userName,client);
int size = clientsMap.size();
System.out.println("当前聊天室有"+size+"人");
String userOnline = userName+"上线了";
System.out.println(userName+"上线了");
GroupChat(userOnline);
}
/**
* 群聊流程
*/
private void GroupChat(String msg){
Collection<Socket> clients = clientsMap.values();
for (Socket client : clients){
try {
PrintStream out = new PrintStream(client.getOutputStream(),true,"UTF-8");
out.println("群聊信息为:"+msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 私聊流程
* @param userName
* @param msg
*/
private void privateChat(String userName, String msg){
Socket client = clientsMap.get(userName);
try {
PrintStream out = new PrintStream(client.getOutputStream(),true,"UTF-8");
out.println(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 退出流程
* @param userName
*/
private void userExist(String userName){
clientsMap.remove(userName);
String groupChatMsg = userName+"已下线";
GroupChat(groupChatMsg);
}
}
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(6666);
ExecutorService service = Executors.newFixedThreadPool(20);
for(int i = 0; i<20; i++){
System.out.println("等待客户端连接");
Socket client = serverSocket.accept();
System.out.println("有新客户端连接,端口号为:"+client.getPort());
service.submit(new ExectueClientRequest(client));
}
}
}
如有不足之处还请见谅,谢谢