主要流程:
思路:
1.创建一个message类用于存储客户端身份信息。
private String userName;//用户名
private long userID;//用户ID
private long messageID;//消息ID
private long groupID;//分组ID,用于群聊
private long friendID;//好友ID,用于一对一聊天
private boolean isGroup;//用于判断是否群聊
private boolean isFirst;
private int chatType;
private String content;// 文本消息内容
private String errorMsg;// 错误信息
private int errorCode;// 错误代码
MessageBean.java
package com.ysu.chatroom0806;
public class MessageBean {
private String userName;//用户名
private long userID;//用户ID
private long messageID;//消息ID
private long groupID;//分组ID,用于群聊
private long friendID;//好友ID,用于一对一聊天
private boolean isGroup;//用于判断是否群聊
private boolean isFirst;
private int chatType;
private String content;// 文本消息内容
private String errorMsg;// 错误信息
private int errorCode;// 错误代码
public long getMessageID() {
return messageID;
}
public void setMessageID(long messageID) {
this.messageID = messageID;
}
public long getGroupID() {
return groupID;
}
public void setGroupID(long groupID) {
this.groupID = groupID;
}
public boolean isGroup() {
return isGroup;
}
public void setGroup(boolean isGroup) {
this.isGroup = isGroup;
}
public int getChatType() {
return chatType;
}
public void setChatType(int chatType) {
this.chatType = chatType;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public long getUserID() {
return userID;
}
public void setUserID(long userID) {
this.userID = userID;
}
public boolean isFirst() {
return isFirst;
}
public void setFirst(boolean isFirst) {
this.isFirst = isFirst;
}
public long getFriendID() {
return friendID;
}
public void setFriendID(long friendID) {
this.friendID = friendID;
}
}
服务器端代码:
ChatServer.java
package com.ysu.chatroom0806;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
public class ChatServer {
private ServerSocket server;
public Gson gson = new Gson();
public Map<Integer, MessageBean> Messagemap = new HashMap<Integer, MessageBean>();
public Map<Integer, Socket> SocketMap=new HashMap<Integer, Socket>();
public List<Socket> listSocket=new ArrayList<Socket>();
public void initServer() {
try {
server = new ServerSocket(SocketUrls.PORT);
createMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 创建消息管理,一直接收消息
*/
private void createMessage() {
Socket socket = null;
try {
System.out.println("等待用户接入 : ");
// 使用accept()阻塞等待客户请求
socket = server.accept();
listSocket.add(socket);
System.out.println("用户接入 : " + socket.getPort());
// 开启一个子线程来等待另外的socket加入
new Thread(new Runnable() {
public void run() {
createMessage();
}
}).start();
// 向客户端发送信息
// final OutputStream output = socket.getOutputStream();
// 从客户端获取信息
BufferedReader bff = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// 读取发来服务器信息
String line = null;
// 循环一直接收当前socket发来的消息
// System.out.println("内容 : " + bff.readLine());
// 获取客户端的信息
//PrintWriter write=new PrintWriter(socket.getOutputStream());
line = bff.readLine();
MessageBean messageBean = gson.fromJson(line, MessageBean.class);
if(messageBean.isFirst()){
setUserInforSocket(messageBean,socket);
//System.out.println("OK");
}
while (!messageBean.getContent().equals(null)&&!messageBean.getContent().equals("")&&!messageBean.getContent().equals("end")){
if(!messageBean.getContent().equals("&")){
System.out.println("用户 : " + messageBean.getUserName());
System.out.println("内容 : " + messageBean.getContent());
findFriend((int) messageBean.getFriendID(),messageBean);
}
line = bff.readLine();
messageBean = gson.fromJson(line, MessageBean.class);
}
// server.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("错误 : " + e.getMessage());
}
}
//将客户端信息存储起来
private void setUserInforSocket(MessageBean message,Socket socket){
if (message != null && Messagemap.get(message.getUserID()) == null&& SocketMap.get(message.getUserID()) == null) {
Messagemap.put((int) message.getUserID(), message);
SocketMap.put((int) message.getUserID(), socket);
}
}
//通过friendID寻找通信对象,将message对象存储的消息取出,传递出去
private void findFriend(int id,MessageBean messageBean){
if(SocketMap.get(id)!=null && SocketMap!=null){
Socket socket=SocketMap.get(id);
MessageBean M=Messagemap.get(id);
M.setContent(messageBean.getContent());
try {
PrintWriter write0=new PrintWriter(socket.getOutputStream());
String t=gson.toJson(M);
String s=gson.toJson(messageBean);
System.out.println(t);
System.out.println(s);
write0.println(s);
write0.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new ChatServer().initServer();
}
}
存储端口号与地址
SocketUrls.java
package com.ysu.chatroom0806;
public class SocketUrls {
// ip地址
public final static String IP = "127.0.0.1";
// 端口号
public final static int PORT = 4443;
}
客户端代码:
ChatClient .java
package com.ysu.chatroom0806;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import com.google.gson.Gson;
public class ChatClient {
private Socket socket;
//每一个客户端拥有一个message对象,象征着身份信息
private MessageBean message;
//GSON是Google开发的Java API,用于转换Java对象和Json对象。
private Gson gson = new Gson();
private int number;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public ChatClient(int num,int id) {
message = new MessageBean();
this.number = num;
message.setFriendID(id);
try {
socket = new Socket(SocketUrls.IP, SocketUrls.PORT);
intiMessage();
System.out.println(message.getUserName()+"已连接服务器");
//接收与转发数据各开一个线程,实现异步交互
receiveMessage();
sendMessage();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 初始化用户基本信息
private void intiMessage() {
message.setUserID(this.number);
message.setGroupID(1);
message.setUserName("admin"+this.number);
message.setMessageID(2);
message.setChatType(1);
message.setFirst(true);
message.setContent("&");
}
// 开个线程接收消息
private void receiveMessage() {
new Thread(new Runnable() {
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run() {
try {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String line ;
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
line = in.readLine();
//System.out.println(line);
while (line != null) {
MessageBean messageBean = gson.fromJson(line, MessageBean.class);
System.out.println("用户 : " + messageBean.getUserName());
System.out.println("内容 : " + messageBean.getContent());
line = in.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
private void sendMessage() {
new Thread(new Runnable() {
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter write = new PrintWriter(socket.getOutputStream());
String GSON = gson.toJson(message);
write.println(GSON);
write.flush();
//System.out.println("请输入好友ID");
//message.setFriendID(Integer.parseInt(br.readLine()));
System.out.println("请输入内容");
String str = br.readLine();
message.setFirst(false);
//System.out.println(str);
while (str != null && !str.equals("end")) {
//System.out.println(str);
message.setContent(str);
//System.out.println(message.getContent());
GSON = gson.toJson(message);
//System.out.println(GSON);
write.println(GSON);
write.flush();
System.out.println("请输入内容");
str = br.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
public static void main(String[] args) {
new ChatClient(1,2);
}
}
运行效果图:
服务器:
admin1:
admin2: