标签:
Socket开发其实很简单
用一个java应用程序模拟一个服务器端:
package mySocketServer; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.httpclient.HttpException; public class StubSocketServer { public static void main(String args[]) throws ParseException { StubSocketServer manager = new StubSocketServer(); manager.doListen(); } public void doListen() { ServerSocket server = null; try { server = new ServerSocket(4700); while (true) { Socket client = server.accept(); new Thread(new SSocket(client)).start(); } } catch (IOException e) { e.printStackTrace(); } finally { try { server.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * <p> * Title: 服务器进程 * </p> */ class SSocket implements Runnable { Socket client; public SSocket(Socket client) { this.client = client; } public void run() { DataInputStream input; DataOutputStream output; try { input = new DataInputStream(client.getInputStream());// 接收对象 output = new DataOutputStream(client.getOutputStream());// 回执对象 byte[] b = new byte[1024]; int msg = input.read(b);// 接收报文 System.out.println("msg===\n" + new String(b, 0, msg, "UTF-8")); new Thread().sleep(5000);// 暂停1分钟60000 if (msg > 0) { output.write("0012600112345600".getBytes("UTF-8")); output.flush(); } } catch (IOException e) { e.printStackTrace(); System.out.println("读取报文没有成功----"); } catch (InterruptedException e) { e.printStackTrace(); } } } }
然后再做一个模拟的客户端,填上你的主机IP和监听的端口号就可以运行了:
Charset charset = Charset.forName("UTF-8"); String src="send content"; byte[] bytes = src.getBytes(charset); Socket socket = new Socket(serverIP, serverPort); byte[] ret = new byte[20]; try { OutputStream os = socket.getOutputStream(); InputStream is = socket.getInputStream(); os.write(bytes); os.flush(); is.read(ret); } finally { socket.close(); }
标签:
原文地址:http://www.cnblogs.com/hehongtao/p/5069624.html