首页 > 代码库 > ServerSocket
ServerSocket
All of codes are from GeekAcademy.
Use ServerSocket to create a chat server - 1
MyServerSocket.java
public class MyServerSocket { public static void main(String[] args) { new ServerListener().start(); } }
ServerListener.java
public class ServerListener extends Thread { @Override public void run() { try { ServerSocket serverSocket = new ServerSocket(12345); while(true){ Socket socket = serverSocket.accept(); JOptionPane.showMessageDialog(null, "A client connects to the local port 12345"); new ChatSocket(socket).start(); } } catch (IOException e) { e.printStackTrace(); } } }
ChatSocket.java
public class ChatSocket extends Thread { Socket socket; public ChatSocket( Socket s) { this.socket = s; } public void out(String out) { try { socket.getOutputStream().write(out.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { int count = 0; while(true){ count++; out("loop: " + count + " "); try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }
ServerSocket
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。