JAVA SOCKET实现一对一TCP实时聊天
思路
首先实时聊天,大致分为2个线程,
- 用户输入线程(主线程),用于用户输入文字并发送。
- 用户接受消息线程(子线程),当由消息来了显示在窗口。
详解
通过qq聊天梳理大致过程三个过程:登录、选择用户。
登录:登录后,我们可以实时接受到其他用户的消息,且不影响主线程,所以当启动一个客户端,就要开启一个线程,线程中用 ServerSocket监听一个端口,用于接受消息
选择用户: 不通用户的识别是ip+端口, 用Socket向其他用户发送消息
用户类
/*
用户类
*/
public class LiveChatUser {
/*
用于接受消息
*/
private final ReceiveMesThread receiveMesThread;
/*
初始化接受消息线程
*/
public LiveChatUser(int port) throws Exception{
this.receiveMesThread = new ReceiveMesThread(port);
this.receiveMesThread.start();
}
/*
选择其他用户,连接上对方,开始聊天
*/
public void connectSocket(String toIp, int toPort) throws Exception{
//连接
SendPoint sendPoint = new SendPoint(toIp, toPort);
//开始聊天
sendPoint.startChat();
//关闭
this.receiveMesThread.closed();
}
}
接受消息线程
/*
接受消息线程
*/
public class ReceiveMesThread extends Thread {
/*
socket服务器
*/
private final ServerSocket server;
/*
运行
*/
private boolean isRun = true;
public ReceiveMesThread(int port) throws Exception{
this.server = new ServerSocket(port);
}
public void closed(){
this.isRun = false;
}
@Override
public void run() {
while(isRun){
try {
Socket accept = server.accept();
InputStream is = accept.getInputStream();
byte[] bytes = new byte[1024];
is.read(bytes);
System.out.println("接收到消息:"+new String(bytes));
}catch (Exception e){
e.printStackTrace();
}
}
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
发送消息类
/**
*
* 发送消息类
*/
public class SendPoint {
private final Socket socket;
private final BufferedReader reader;
public SendPoint(String toIp, int toPort) throws Exception{
socket = new Socket(toIp,toPort);
reader = new BufferedReader(new InputStreamReader(System.in));
}
public void startChat() throws Exception{
while (true){
String content = reader.readLine();
System.out.println(" 发送消息:"+content);
byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
OutputStream os = socket.getOutputStream();
os.write(bytes);
os.flush();
if(content.equals("bye")){
break;
}
}
closed();
}
public void closed() throws Exception{
socket.close();
}
}
测试模拟用户1和用户2聊天
/**
*
* 用户1
*/
public class User01 {
public static void main(String[] args) throws Exception {
LiveChatUser liveChatUser = new LiveChatUser(10001);
System.out.println("输入对方ip");
Scanner scanner = new Scanner(System.in);
String ip = scanner.nextLine();
System.out.println("输入对方端口");
int port = scanner.nextInt();
liveChatUser.connectSocket( ip, port);
}
}
/**
*
* 用户2
*/
public class User02 {
public static void main(String[] args) throws Exception {
LiveChatUser liveChatUser = new LiveChatUser(10002);
System.out.println("输入对方ip");
Scanner scanner = new Scanner(System.in);
String ip = scanner.nextLine();
System.out.println("输入对方端口");
int port = scanner.nextInt();
liveChatUser.connectSocket(ip, port);
}
}
- 启动两个java类,(注意必须先启动2个用户类,tcp是可靠连接,必须确保对方socket应用存在)
2.选择好友(通过ip加端口)
3. 发送消息