承接上一篇文章,今天谈论一下可以多客户端链接的ServerSocket。
这里面注意涉及到的技术点是:
1.ServerSocket
2.多线程
这次我们分成两个类来实现,先上代码:
package com.test.socket; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner; public class ThreadedEchoHandler implements Runnable { private Socket socket = null; public ThreadedEchoHandler(Socket s) { this.socket = s; } @Override public void run() { InputStream inputStream; try { inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); Scanner scanner = new Scanner(inputStream); PrintWriter printWriter = new PrintWriter(outputStream, true); printWriter.println("welcome to testServer"); boolean done = false; while (!done && scanner.hasNextLine()) { String line = scanner.nextLine(); printWriter.println("Echo:" + line); if (line.trim().equals("bye")) { done = true; } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }ThreadedEchoHandler类主要实现的功能跟上一篇差不多,都是接受客户端发过来的数据,然后复制一下打印出来,但是这里面继承了Runnable,可以支持多线程
package com.test.socket; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class TestSocket { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(8189); while (true) { Socket socket = serverSocket.accept(); ThreadedEchoHandler handler = new ThreadedEchoHandler(socket); Thread thread = new Thread(handler); thread.start(); } } }
扩展一下,这里的测试类只是用来测试用的,如果考虑到性能的问题,这里一般会采取线程池,而且还需要有检测链接是否还在的检测类,不然随着客户端链接的增加,内存直接爆掉。
而且这两个类还欠缺了一些东西,譬如客户端怎样退出?检测链接?半关闭?等等,这些后面待续
版权声明:本文为博主原创文章,未经博主允许不得转载。
java基础入门-建立可以多客户端链接的ServerSocket
原文地址:http://blog.csdn.net/raylee2007/article/details/47087453