一起来学FIX协议(2)——登录

package test;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LoginTest {
    private static Socket socket;

    public static void main(String[] args) throws UnknownHostException,
            InterruptedException {
        SimpleDateFormat foo = new SimpleDateFormat("yyyyMMdd-HH:mm:ss.SSS");

        String SOH = "\u0001"; //SOH,其实就是二进制的0x01

        String loginMessage = "35=A" + SOH + "49=yourusername" + SOH
                + "56=sendersubid" + SOH + "34=" + 1 + SOH
                + "50=targetcompid" + SOH + "52=" + foo.format(new Date())
                + SOH + "98=0" + SOH + "108=60" + SOH + "96=password" + SOH
                + "141=Y" + SOH; //Body,需要根据协议要求来组幁
        loginMessage = "8=FIX.4.2" + SOH + "9=" + loginMessage.length() + SOH
                + loginMessage; //Header + Body,需要根据协议要求来组幁

        loginMessage += "10=" + Utils.checkSum(loginMessage) + SOH; //Header + Body + Tail

        try {
            socket = new Socket("127.0.0.1", 8080); //服务器IP和地址,这里采用TCP

            DataInputStream in = new DataInputStream(socket.getInputStream());

            DataOutputStream out = new DataOutputStream(
                    socket.getOutputStream());
            out.writeBytes(loginMessage);
            out.flush();

            byte[] buffer = new byte[10240];
            int byteRead = in.read(buffer);
            String msg = new String(buffer);

            System.out.println("<---   " + msg);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

其中checksum函数见:http://blog.csdn.net/donhao/article/details/7841703

你可能感兴趣的:(Financial,Java)