📄 server.java
字号:
package day15.chat;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintStream;import java.net.ServerSocket;import java.net.Socket;import java.util.HashMap;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JOptionPane;import day15.net.ServerThread;public class Server { JFrame jf=new JFrame("聊天室服务器"); HashMap hm=new HashMap(); JOptionPane jop=new JOptionPane(); private static String word=""; public Server(){ JButton jbStart=new JButton("确认"); } public void startServer(){ ServerSocket ss = null; try { ss = new ServerSocket(7456); } catch (IOException e) { System.out.println("端口被占用"); } System.out.println("begin"); while(true){ Socket so = null; try { so = ss.accept(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }//在这里停住,直到客户 ServerThread st=new ServerThread(so); st.start(); } } class ServerThread extends Thread{ private Socket so; public ServerThread(Socket so){ this.so=so; } public void run(){ System.out.println("stop"); try{ InputStreamReader isr = new InputStreamReader(so.getInputStream()); BufferedReader br=new BufferedReader(isr);//读 PrintStream ps = new PrintStream(so.getOutputStream()); while(true){ synchronized(this){ String temp = br.readLine(); if("\u0004".equals(temp)){//如果是刷新指令 ps.println(word);//写回 System.out.println("Fresh"); } else/*(!"\u0000".equals(temp))*/ {//客户的消息 System.out.println(temp); if("bye".equals(temp)){ break; } word=temp+"\u0001"+word; ps.println(word);//写回 System.out.println("Not Fresh"); } } } br.close(); isr.close(); ps.close(); so.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } class UserIno{ public PrintStream ps;//用于保存连接用户的输出的流 public int time;//用于标识用户是否在线, 间隔一段时间会自动减少 } } public static void main(String[] args) throws IOException { new Server().startServer(); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -