这几天有点精神萎靡的症状,突然想起了Socket,想用Perl实现下,但是发现有很多问题。没有解决好。
所以用Java实现一下,看看有什么共同点。
不过没有来得及写注释,现学现卖把。回头改下就能传日志了。。
Server端代码如下:
package com.service; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class ServerMain { /** * @param args */ public static void main(String[] args) throws Exception{ ServerSocket socketServer=new ServerSocket(9881); while(true){ System.out.println("server ok! "); Socket socket=socketServer.accept(); InputStream in=socket.getInputStream(); byte[] b=new byte[7]; int len; try{ while((len=in.read(b))!=-1){ String value=new String(b,0,len); double d =Double.parseDouble(value); System.out.println(d); } }catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } } }
Client代码如下:
package com.client; import java.io.OutputStream; import java.net.Socket; public class ClientMain { static class SendThread extends Thread{ Socket server; byte[] value; public SendThread(Socket server,String value){ this.server=server; this.value=value.getBytes(); } public void run(){ while(true){ try{ OutputStream out=server.getOutputStream(); out.write(value); out.flush(); Thread.sleep(1000); }catch (Exception e) { // TODO: handle exception return; } } } } /** * @param args */ public static void main(String[] args) throws Exception{ Socket server =new Socket("localhost",9881); SendThread t1=new SendThread(server, "123.123"); SendThread t2=new SendThread(server,"321.332"); t1.start(); t2.start(); } }