Java单线程程序实现实现简单聊天功能
更新时间:2020年10月27日 15:25:47 作者:wangchw
这篇文章主要介绍了Java单线程程序实现实现简单聊天功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
信息发送
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class May {
public static void main(String[] args) {
// 单线程程序
try {
ServerSocket socket = new ServerSocket(2233);//端口号
Socket soc = socket.accept();
// 读取信息
BufferedReader br = new BufferedReader(new InputStreamReader(soc.getInputStream()));
PrintWriter out = new PrintWriter(soc.getOutputStream());
while (true) {
// 发送
System.out.println("发送:");
String msg = new Scanner(System.in).nextLine();
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
out.println(String.format("[%s]:%s\r\n", "服务器", msg));
out.flush();
// 接收
System.out.println(br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
接收信息并回复
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Max {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost",2233);//链接端口号
String sc = s.getInetAddress().getHostAddress();//获取IP
// 读取信息
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream());
while (true) {
// 接收
System.out.println(br.readLine());
// 发送
System.out.println("发送:");
String msg = new Scanner(System.in).nextLine();
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
out.println(String.format("[%s]:%s\r\n", sc, msg));
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
发送你好

接收你好并回复
[/code]
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Spring Security拦截器引起Java CORS跨域失败的问题及解决
这篇文章主要介绍了Spring Security拦截器引起Java CORS跨域失败的问题及解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-07-07
SpringBoot整合WebSocket实现聊天室流程全解
WebSocket协议是基于TCP的一种新的网络协议。本文将通过SpringBoot集成WebSocket实现简易聊天室,对大家的学习或者工作具有一定的参考学习价值,感兴趣的可以了解一下2023-01-01
Springboot导入本地jar后 打包依赖无法加入的解决方案
这篇文章主要介绍了Springboot导入本地jar后 打包依赖无法加入的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-11-11


最新评论