服务器和客户端之间的协议:
二进制协议,每条第一个字节为协议名字字节,表明协议的类型。每种类型的协议有固定的长度。
例如:
命令字节 长度  内容                                                           含义 
01        17   以0x00结尾的字符串,代表别名                                   登陆 
02        17   以0x00结尾的字符串,代表别名                                   退出 
21        98   char* alias, char* content,以0x00结尾的字符串,代表输入的文字  文字输入  很多socket例子都是直接传递字符串并显示。这里该如何传递数据并解析。

解决方案 »

  1.   

    Socket 是通过输入输出流来接收和发送字节的。
    http://blog.csdn.net/YidingHe/archive/2009/04/20/4093892.aspx
      

  2.   

    使用DataInputStream读取clent使用DataOutputStream压入数据,如登录 01,长度占17个字节,在数据管道中处于第一个位置,server端使用DataInputStream的readFully(buff,0,17)读取命令,17个字节后面是什么数据,多少长度,在管道中那个位置,client、server都需要有明确的约定 [ 命令(17) | 内容(32) | 响应(10) | ...]类型与MM2协议
      

  3.   

    public class Server { private DataInputStream dis = null; public void start() throws IOException {
    ServerSocket ss = new ServerSocket(20002);
    Socket socket = ss.accept();
    InputStream in = socket.getInputStream();
    dis = new DataInputStream(in);
    byte status = dis.readByte();
    System.out.println("状态:" + status);

    if (status == 0x01) {
    handle(17);
    } } public void handle(int length) throws IOException {
    byte[] msg = new byte[length - 1];
    dis.read(msg);
    System.out.println(new String(msg));
    } public static void main(String[] args) throws IOException {
    System.out.println("Server start...");
    Server s = new Server();
    s.start();
    }
    }public class Client {
    private Socket socket = null;

    public void connect() throws UnknownHostException, IOException{
    socket = new Socket("localhost",20002);
    OutputStream out = socket.getOutputStream();
    DataOutputStream dos = new DataOutputStream(out);
    byte[] str = "这是一个测试用的".getBytes();
    int length = str.length;
    byte[] msg = new byte[length + 1];
    msg[0] = 0x01; System.arraycopy(str, 0, msg, 1, length);

    for (int i = 0; i < msg.length; i++) {
    System.out.print(msg[i] + " ");
    }
    dos.write(msg);
    }

    public static void main(String[] args) throws UnknownHostException, IOException {
    Client c = new Client();
    c.connect();
    }
    }
      

  4.   

    你可以使用特殊分隔符或者使用XML格式流进行传输。注意先定义好接口文档。呵呵。