Niceri

导航

Asp.Net项目与TCP服务端交互

    private void SocketSend(string sendstr)
    {
        //将字符串转换成字节数组
        Byte[] fsSize = System.Text.Encoding.Default.GetBytes(sendstr);

        //创建发送数据的Socket
        Socket sendsocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

        //设置发送数据的地址  
        IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10001);

        try
        {
            //连接TCP服务端
            sendsocket.Connect(endPoint);
            if (sendsocket.Connected)//连接成功
            {
                //发送数据
                int length = sendsocket.Send(fsSize);

                //接收返回的数据
                byte[] reutrns = new byte[1024];
                //设置接收超时的时间 如果超出会报SocketException 错误
                sendsocket.ReceiveTimeout = 1800;
                while (true)
                {
                    //返回接收到数据的长度
                    int reLength = sendsocket.Receive(reutrns, 0, sendsocket.Available, SocketFlags.None);
                    if (reLength>0)//如果接收到数据
                        break;
                }

                //将返回的字节转换为string 类型
                string ss = System.Text.Encoding.UTF8.GetString(reutrns);
                //判断如果回复的字节正确"ok"
                if (ss == "ok")
                {                  
                    //执行操作
                }
            }
            else
            {
               //连接失败 记录日志
            }        
        }
        catch (SocketException ex)
        {
            int exint = ex.ErrorCode;//分析返回错误码 并记录
        }
        finally {
            //关闭发送数据的Socket
            sendsocket.Shutdown(SocketShutdown.Send);
            sendsocket.Close();
        }
    }

  

posted on 2017-07-25 14:57  Niceri  阅读(502)  评论(0编辑  收藏  举报