码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-01-14 23:17:38      阅读:828      评论:0      收藏:0      [点我收藏+]

标签:com   tar   work   cmd   serve   rip   lis   exception   dso   

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);
        }
    }

 

  

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

标签:com   tar   work   cmd   serve   rip   lis   exception   dso   

原文地址:https://www.cnblogs.com/timy/p/10269260.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!