可以用类似 while(true)input.readByte()来想得到客户端发送过来的数据。 用output的writeByte来像客户端发送数据。
服务器的socket是通过serverSocket.accept()方法来产生的。
用这个类实现线程池。
看例子,如下代码实现的功能很简单,就是客户端发送一个字节,服务器读到客户端发送的数据后打印它。
代码如下 | 复制代码 |
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; class NetworkService implements Runnable { private final ServerSocket serverSocket; private final ExecutorService pool; public NetworkService(int port, int poolSize) throws IOException { serverSocket = new ServerSocket(port); pool = Executors.newFixedThreadPool(poolSize); } public void run() { // run the service try { for (;;) { pool.execute(new Handler(serverSocket.accept())); } } catch (IOException ex) { pool.shutdown(); } } public static void main(String[] args) { NetworkService ns = null; try { ns = new NetworkService(400, 5); } catch (IOException e) { e.printStackTrace(); } new Thread(ns).start(); } } class Handler implements Runnable { private final Socket socket; private DataInputStream input; private DataOutputStream output; Handler(Socket socket) { this.socket = socket; try { input =new DataInputStream(socket.getInputStream()); output = new DataOutputStream(socket.getOutputStream()); System.out.println("new connect"); } catch (Exception e) { e.printStackTrace(); } } public void run() { int data; while(true){ try { data = input.readByte(); System.out.println(data); } catch (IOException e) { break; } } System.out.println("close"); try { input.close(); } catch (IOException e) { e.printStackTrace(); } try { output.close(); } catch (IOException e) { e.printStackTrace(); } try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } |
客户端
代码如下 | 复制代码 |
var socket:Socket=new Socket(400); socket.addEventListener("connect",function():void{socket.writeByte(100)}); |
时间: 2024-09-20 05:40:51