日期:2014-05-19 浏览次数:20774 次
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; public class serverS { public static void main(String[] args) throws IOException,InterruptedException { serverS s = new serverS(); s.start(4342); } // 这里存放请求的clientSocket List<ClientThread> clientList = new ArrayList<ClientThread>(); public void start(int port) throws IOException, InterruptedException { ServerSocket server = new ServerSocket(port); while (true) { Socket clientSocket = server.accept(); ClientThread client = new ClientThread(clientSocket); clientList.add(client); client.start(); Thread.sleep(2000); for (ClientThread c : clientList) { c.send(); } } } } /** * 把请求的的socket封装成对像,分别处理 接收 和 发送 * @author GKT * */ class ClientThread extends Thread { private InputStream inputStream; private OutputStream outputStream; public ClientThread(Socket client) throws IOException { this.inputStream = client.getInputStream(); this.outputStream = client.getOutputStream(); } /** * 这里向client发消息 * @throws IOException */ public void send() throws IOException { outputStream.write(222); System.out.println("callClient"); } /** * 这时处理client传来的消息,注意保持长链接,client端也要保持 */ public void run() { System.out.println("用户连接"); while (true) { try { if (inputStream.available() > 0) { System.out.println(inputStream.read()); } else { Thread.sleep(3000); } } catch (Exception e) { System.out.println("用户退出"); break; } } } }