栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

通过套接字将多个客户端编程到一台服务器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

通过套接字将多个客户端编程到一台服务器

对于每个客户端,你需要启动单独的线程。例:

public class ThreadedEchoServer {    static final int PORT = 1978;    public static void main(String args[]) {        ServerSocket serverSocket = null;        Socket socket = null;        try { serverSocket = new ServerSocket(PORT);        } catch (IOException e) { e.printStackTrace();        }        while (true) { try {     socket = serverSocket.accept(); } catch (IOException e) {     System.out.println("I/O error: " + e); } // new thread for a client new EchoThread(socket).start();        }    }}

public class EchoThread extends Thread {    protected Socket socket;    public EchoThread(Socket clientSocket) {        this.socket = clientSocket;    }    public void run() {        InputStream inp = null;        BufferedReader brinp = null;        DataOutputStream out = null;        try { inp = socket.getInputStream(); brinp = new BufferedReader(new InputStreamReader(inp)); out = new DataOutputStream(socket.getOutputStream());        } catch (IOException e) { return;        }        String line;        while (true) { try {     line = brinp.readLine();     if ((line == null) || line.equalsIgnoreCase("QUIT")) {         socket.close();         return;     } else {         out.writeBytes(line + "nr");         out.flush();     } } catch (IOException e) {     e.printStackTrace();     return; }        }    }}

你还可以使用更高级的解决方案,该解决方案使用NIO选择器,因此你不必为每个客户端创建线程,但这要复杂一些。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/441956.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号