C#进行Socket 连接发送和接收数据

/// <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\n" + ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    finally
    {
        this.btn_submit.Enabled = true;
    }
}

转载于:https://my.oschina.net/Kxvz/blog/607840

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值