Client:
1.使用Socket类
if (socket == null) socket = new Socket(address, 2333);//不要用1024之前的端口
2.socket通过对其中的outputstream和inputstream操作实现通讯
if (writer == null) writer = new PrintWriter(socket.getOutputStream()); writer.println(toSend); writer.flush();//一定要记得flush刷新
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); while(!socket.isClosed()) { sleep(100); String line = reader.readLine(); if(line!=null){ textArea.append(line + "\n"); } } reader.close();
3.修改JFrame默认关闭窗口事件
addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { super.windowClosing(e); try { if (socket != null) { socket.close(); } } catch (Exception ex) { ex.printStackTrace(); } System.exit(0); } });
Server:
1.使用ServerSocket
serverSocket = new ServerSocket(2333);
2.广播实现
socketList = new ArrayList<Socket>(); try { serverSocket = new ServerSocket(2333); while (true) { Socket socket = serverSocket.accept(); if(!socketList.contains(socket)){ socketList.add(socket); new SocketThread(socket); } } } catch (Exception e) { e.printStackTrace(); }
3.使用多线程
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); while (socket.isClosed() == false) { sleep(100); String line = reader.readLine(); if (line != null) { for (int i = 0; i < socketList.size(); i++) { Socket iter = (Socket) socketList.get(i); PrintWriter writer = new PrintWriter(iter.getOutputStream()); System.out.println(line); writer.println(line); writer.flush(); } } } socketList.remove(socket);
在室友电脑上初次运行客户端时无法访问到我的服务器,把我的Server打成jar包后运行把防火墙取消后成功完成了通讯!
时间: 2024-10-01 08:06:37