C#Socket接続によるデータの送受信

2357 ワード

/// <summary>
///   
/// </summary>
/// <param name="b"></param>
/// <returns></returns>
private int byte2Int(byte[] b)
{
    return ((b[0] & 0xff) << 24) | ((b[1] & 0xff) << 16)
            | ((b[2] & 0xff) << 8) | (b[3] & 0xff);
}

/// <summary>
///  
/// </summary>
/// <param name="a"></param>
/// <returns></returns>
private byte[] int2Byte(int a)
{
    byte[] b = new byte[4];
    b[0] = (byte)(a >> 24);
    b[1] = (byte)(a >> 16);
    b[2] = (byte)(a >> 8);
    b[3] = (byte)(a);

    return b;
}

/// <summary>
///  Socket 
/// </summary>
/// <param name="ip"></param>
/// <param name="port"></param>
/// <returns></returns>
private void readSocketData(String ip,int port,String requestData){
    try
    {
        IPAddress ipAddress = IPAddress.Parse(ip);
        Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        clientSocket.ReceiveTimeout = 5000;
        clientSocket.SendTimeout = 5000;
        clientSocket.Connect(new IPEndPoint(ipAddress, port));

        Task<String> readRes = Task.Factory.StartNew<String>(() =>
        {
            byte[] result = new byte[40960];

            clientSocket.Receive(result);
            int receiveLength = byte2Int(result);
            String response = Encoding.UTF8.GetString(result, headLength, receiveLength);
            return response;
        });

        byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(requestData);
        int length = byteArray.Length;
        byte[] lenBytes = int2Byte(length);
        byte[] newBytes = new byte[lenBytes.Length + length];
        lenBytes.CopyTo(newBytes, 0);
        byteArray.CopyTo(newBytes, lenBytes.Length);
        clientSocket.Send(newBytes);

        string resultStr = readRes.Result;
        MessageBox.Show(resultStr, "Socket Result", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    catch (Exception ex)
    {
        MessageBox.Show("Socket connect fail.\r
" + ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);     }     finally     {         this.btn_submit.Enabled = true;     } }