教育路上
摘要:java在线聊天室服务端Server类的创建。以下是我们为大家整理的,相信大家阅读完后肯定有了自己的选择吧。
2021-06-29 11:53网络推荐
package aaa; import java.awt.*; import java.awt.event.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.HashMap; import java.util.Set; import javax.swing.*; public class server extends JFrame { private ServerSocket serversocket; private Socket client; private int ports=8080; private HashMap<String,Socket> userlist=new HashMap(); server(){ gui(); listion(); waitsocket(); flashchart(); } //图形界面 void gui(){ JFrame f=new JFrame("服务端"); f.setSize(300,200); f.setLocation(300,200); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } //服务端 void listion() { try { serversocket=new ServerSocket(ports); } catch (IOException e) { e.printStackTrace(); } } //等待客户端连接 void waitsocket() { new Thread() { public void run() { while(true) { System.out.println(serversocket); if(serversocket!=null) { try { client= serversocket.accept(); }catch(Exception e1) { return; } } } } }.start(); } void flashchart(){ new Thread() { public void run() { while(true) { System.out.println(client); if(client!=null) { String str; try { BufferedReader reader = new BufferedReader(new InputStreamReader(client .getInputStream())); str=reader.readLine(); }catch(Exception e1) { return; } String[] arr=str.split("@"); String usrename = arr[0]; String message = arr[1]; String status = arr[2]; //zhangshan@@reg //zhangshan@聊天内容@all //zhangshan@聊天@wang if(status.equals("reg")) { Set<String> keyset=userlist.keySet(); int a=0; for(String user:keyset) { if(user.equals(usrename)) { a=1; break; } } if(a==0) { userlist.put(usrename, client); } String userflash=null; for(String user:keyset) { userflash=userflash+"@"+user; } userflash=userflash+"@userlist"; for(String user:keyset) { try { PrintWriter writer = new PrintWriter(userlist.get(user).getOutputStream()); writer.println(userflash); writer.flush(); }catch(Exception e1) { return; } } }else if(status.equals("所有人")) { Set<String> keyset=userlist.keySet(); for(String user:keyset) { try { String allchart=usrename+"@对所有人说:"+message+"@群发聊天"; PrintWriter writer = new PrintWriter(userlist.get(user).getOutputStream()); writer.println(allchart); writer.flush(); }catch(Exception e1) { return; } } }else{ Set<String> keyset=userlist.keySet(); for(String user:keyset) { try { if(status.equals(user)) { String allchart=usrename+"@对"+status+"说:@"+message; PrintWriter writer = new PrintWriter(userlist.get(user).getOutputStream()); writer.println(allchart); writer.flush(); } }catch(Exception e1) { return; } } } } } } }.start(); } public static void main(String[] args) { new server(); } }
访客的评论 2024/10/04 06:59
文中描述的是准确的吗,如何报名!