package com.zl; import java.net.ServerSocket; import java.net.Socket; import org.apache.commons.mvc.util.FileUtil; public class TestSocket { public static void main(String[] args) { new ServerThread().start(); } } //创建一个线程在后台监听 class ServerThread extends Thread { public void run() { ServerSocket serversocket = null; try { serversocket = new ServerSocket(10000);// 创建一个serversocket对象,并让他在Port端口监听 while (true) { Socket socket = serversocket.accept();// 接收客户端发送的请求 System.out.println(FileUtil.readFile(socket.getInputStream(), null, 1, false)); socket.close(); } } catch (Exception e) { e.printStackTrace(); } finally { try { serversocket.close(); } catch (Exception e) { e.printStackTrace(); } } } }
package com.zl; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; public class Test { public static void main(String[] args) throws Exception { socket(); } public static void socket() { try { Socket socket = new Socket("192.168.1.58", 10000);// 创建socket对象,指定服务器端地址和端口号 OutputStream output = socket.getOutputStream(); PrintWriter out = new PrintWriter(output, true);// 获取 Client 端的输出流 out.print("发送信息内容");// 填充信息 out.flush();out.close(); output.flush();output.close(); socket.close(); } catch (Exception e) { e.printStackTrace(); } } }
comet4j
http://blog.csdn.net/shadowsick/article/details/9014139