JAVA(多人聊天室) 最简单的控制台输出版,NIO单线程服务器,双线程客户端,妈妈再也不担心我不会写聊天室了
程序员文章站
2022-03-11 08:52:28
JAVA(多人聊天室) 最简单的控制台输出版,NIO单线程服务器,双线程客户端,妈妈再也不担心我不会写聊天室了。一、惯例先上效果图:二、代码(开袋即食)2.1 服务端public class NIOServer { static List channelList = new ArrayList<>(); public static void main(String[] args) { try {...
JAVA(多人聊天室) 最简单的控制台输出版,NIO单线程服务器,双线程客户端,妈妈再也不担心我不会写聊天室了。
一、惯例先上效果图:
二、代码(开袋即食)
2.1 服务端
public class NIOServer {
static List<SocketChannel> channelList = new ArrayList<>();
public static void main(String[] args) {
try {
//ServerSocket serverSocket = new ServerSocket(8888);
ServerSocketChannel serverSocket = ServerSocketChannel.open();
SocketAddress socketAddress = new InetSocketAddress(8888);
serverSocket.bind(socketAddress);
serverSocket.configureBlocking(false);
System.out.println("启动服务器。。。。");
while (true) {
//Socket clientSocket = serverSocket.accept();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
// for (SocketChannel socketChannel : channelList) {
for (int i = 0; i < channelList.size(); i++) {
if (channelList.get(i).finishConnect()){
int read = 0;
try {
read = channelList.get(i).read(byteBuffer);
} catch (IOException e) {
System.out.println("客户端断开连接了");
channelList.remove(i);
}
if (read > 0) {
byteBuffer.flip();
byte[] bs = new byte[read];
byteBuffer.get(bs);
String content = new String(bs);
System.out.println(content);
for (int j = 0; j < channelList.size(); j++){
channelList.get(j).write(byteBuffer.wrap(bs));
}
byteBuffer.flip();
} else if (read == -1) {
channelList.remove(i);
}
}
}
//循环等待连接
SocketChannel accept = serverSocket.accept();
if (accept != null) {
System.out.println("连接成功!");
accept.configureBlocking(false);
channelList.add(accept);
System.out.println("当前服务器连接数为:" + channelList.size());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.2 客户端
public class Client {
static Socket socket;
private static void acceptMessage(Socket socket){
try {
while (true){
byte[] bytes = new byte[1024];
socket.getInputStream().read(bytes);
System.out.println(new String(bytes));
}
} catch (IOException e) {
}
}
private static void sendMessage(Socket socket){
try {
Scanner sc = new Scanner(System.in);
System.out.print("请输入您聊天室的昵称:");
String str = sc.nextLine();
System.out.println(str + "欢迎来到聊天室!");
while (true){
String s = str + ":" + sc.nextLine();
if(str.contains("exit")){
System.out.println("断开连接!");
break;
}
socket.getOutputStream().write(s.getBytes());
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static class Tread01 extends Thread{
public void run(){
sendMessage(socket);
}
}
static class Tread02 extends Thread{
public void run(){
acceptMessage(socket);
}
}
public static void main(String[] args) {
try {
socket = new Socket("localhost", 8888);
Tread01 t1 = new Tread01();
Tread02 t2 = new Tread02();
t1.start();
t2.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
本文地址:https://blog.csdn.net/weixin_44197478/article/details/107394195
上一篇: 基于redis实现定时任务的方法详解
下一篇: jdk和cglib代理过程详解