C# Socket的Send问题,阻塞线程

Socket sc = comm.connectSocket(ip, port, ReceiveMsg_fromPc);
comm.sendSocketMsg16(sc,cmd);
sc.Close();
public static Socket connectSocket(string ip, int port, ReceiveSocketMsg receiveMsg)
    {
        Socket socket = null;
        try
        {
            IPAddress serverIP = IPAddress.Parse(ip);
            IPEndPoint serverFullAddr = new IPEndPoint(serverIP, port);//设置IP,端口  
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //指定本地主机地址和端口号  
            socket.Connect(serverFullAddr);

            Thread receiveThread = new Thread(receiveSocketMessage);
            List<Object> list = new List<object>();
            list.Add(socket);
            list.Add(receiveMsg);
            receiveThread.Start(list);
        }
        catch (Exception e)
        {
            MessageBox.Show("未能与" + ip + ":" + port.ToString() + "建立通讯。\r\n请检查目标设备是否已经启动并保持网络畅通!");
        }

        return socket;
    }

 

/// <summary>
    /// 发送16进制消息
    /// </summary>
    /// <param name="socket"></param>
    /// <param name="msg"></param>
    public static void sendSocketMsg16(Socket socket, string msg)
    {
        byte[] byteSend = strToToHexByte(msg);
        byte[] bytes = new byte[256];
        try
        {
            //发送数据  
            //socket.Send(byteSend);

            int i = socket.Send(byteSend, byteSend.Length, SocketFlags.None);

            // Get reply from the server.
            int byteCount = socket.Receive(bytes, socket.Available,SocketFlags.None);

            if (byteCount > 0)
                Console.WriteLine(Encoding.UTF8.GetString(bytes));

        }
        catch (Exception ex)
        {
            //lblError.Text = "出现错误,请联系管理员" + ex;
            MessageBox.Show(ex.Message);
        }
    }

 

  

猜你喜欢

转载自www.cnblogs.com/timy/p/10269260.html
0条评论
添加一条新回复