标签:
用tornado做了个socket server。无奈联调的人员对接不上。
于是撸出了以下demo
import java.io.*;
import java.net.*;
public class SocketTest{
    SocketTest(){}
    void test()
    {
        try{
            Socket requestSocket = new Socket("xxx.xxx.xxx.xxx", 60006);
            OutputStream out = requestSocket.getOutputStream();
            InputStream in = requestSocket.getInputStream();
            byte[] bb = new byte[16] ;
            for(int i =0;i<13;i++)
            {
                bb[i+3]=(byte)((int)‘a‘+i);
            }
            bb[0]=(byte)0x00;
            bb[1]=(byte)0x0e;
            bb[2]=(byte)0xaa;
            bb[15]=(byte)0xfe;
            System.out.println("client>"+new String(bb));
            
            out.write(bb);
            out.flush();
            byte[] buffer = new byte[1024];
            in.read(buffer);
            String responseStr = new String(buffer);
            System.out.println("server>"+responseStr);
            out.close();
            in.close();
            requestSocket.close();
        }
        catch(IOException ioException){
            ioException.printStackTrace();
        }
        // catch(ClassNotFoundException classNot){
        //     System.err.println("data received in unknown format");
        // }
    }
    public static void main(String args[])
    {
        SocketTest client = new SocketTest();
        client.test();
    }
}
既要:
1. linux 下编译执行的细节:
javac SocketTest.java
java SocketTest (不要 java SocketTest.class, 不然一大堆误导加麻烦)
2. 字节操作,在java里面用byte数组,不要担心(128~255)溢出。直接赋值即可。
byte b = (byte)254;
3. 从socket得到原始的输入输出流,不要再用其他包裹,否则会出现诡异的事情。
OutputStream out = requestSocket.getOutputStream();
InputStream in = requestSocket.getInputStream();
标签:
原文地址:http://www.cnblogs.com/Tommy-Yu/p/5342213.html