日期:2014-05-17 浏览次数:20629 次
import java.io.*; import java.net.*; import java.util.*; public class EchoServer { public static final int PORT = 10000; public static void main(String[] args) throws Exception { ServerSocket serverSocket = new ServerSocket(PORT); try { while (true) { System.out.println("服务端就绪,等待客户端连接"); // 侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。 Socket socket = serverSocket.accept(); System.out.println("有客户端连接上来了,已建立Socket链接"); EchoServerWorker worker = new EchoServerWorker(socket); System.out.println("启动工作线程"); new Thread(worker).start(); } } finally { serverSocket.close(); } } } class EchoServerWorker implements Runnable { private Socket socket; // 工作线程所服务的目标Socket EchoServerWorker(Socket socket) { this.socket = socket; } public void run() { try { try { // 准备输入输出端口 Scanner sc = new Scanner(socket.getInputStream()); OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream()); System.out.println("Socket for " + socket.getPort() + " started."); // 读取信息并直接返回,这里按行读取(\n) String str; while ((str = sc.nextLine()) != null) { System.out.println("【From Client】" + str); out.write(str + "\n"); out.flush(); } } finally { socket.close(); System.out.println("Scoket for " + socket.getPort() + " closed."); } } catch (IOException ex) { ex.printStackTrace(); } } }
------解决方案--------------------