c# 使用socket进行tcp通信

 服务端开启监听代码示例:

//服务端开启监听示例
        Socket ListenSocket;
        private void btnStartListen_Click(object sender, EventArgs e)
        {
            if (ListenSocket == null)
            {
                ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress IPAddress = IPAddress.Parse("192.168.1.195");//获取本机ip
                IPEndPoint endpoint = new IPEndPoint(IPAddress, 2333);//网络节点
                ListenSocket.Bind(endpoint);
                ListenSocket.Listen(10);
                Action _a = () =>
                {
                    GetConn(ListenSocket);
                };
                Task.Factory.StartNew(_a);
            }
        }

        Socket GetedSocketConn;
        void GetConn(Socket socket)
        {
            while (true)
            {
                Thread.Sleep(10);
                GetedSocketConn = socket.Accept();//该函数会一直阻塞线程,直到接收到一个新的连接请求
                Console.WriteLine("成功获取连接" + GetedSocketConn.RemoteEndPoint.ToString());
            }
        }

客户端进行连接代码示例(该示例中,使用了绑定IP及端口的模式,非动态获取端口):

        Socket SocketClient;
        private void btnStartConnect_Click(object sender, EventArgs e)
        {
            SocketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            SocketClient.Bind(new IPEndPoint(IPAddress.Parse("0.0.0.0"), 8848));
            try
            {
                IPAddress _otherIPAddress = IPAddress.Parse("192.168.1.195");//获取ip
                IPEndPoint _otherEndpoint = new IPEndPoint(_otherIPAddress, 2333);//网络节点
                SocketClient.Connect(_otherEndpoint);
            }
            catch (Exception ex)
            {
                Console.WriteLine("连接失败:" + ex.ToString());
            }
        }

关闭连接,使用Socket进行tcp通信时,需要客户端与服务器端都进行关闭,已建立的连接才会彻底关闭,否则客户端所绑定的固定端口就一直是在占用状态,无法再次建立新的连接:

//tcp客户端关闭连接代码
        private void btnCloseClient_Click(object sender, EventArgs e)
        {
            if (SocketClient != null)
            {
                SocketClient.Close();
            }
        }

上面的代码执行之后,会发现8848端口处于FIN_WAIT_2状态,需要等待服务器确认关闭连接,才会释放此端口,而再看服务器2333端口为CLOSE_WAIT状态,意为需要调用关闭:

//服务器关闭现有连接
        private void btnCloseServerConn_Click(object sender, EventArgs e)
        {
            if (GetedSocketConn != null)
            {
                GetedSocketConn.Close();
            }
        }

 等到上面的服务器关闭连接的代码也被执行之后,端口会变为如下状态:

客户端绑定的端口8848会变为TIME_WAIT状态,该状态会持续2MSL(即两倍的分段最大生存期)时间,在此期间该端口仍然是被占用状态,直到时间结束,端口彻底释放:

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
进行TCP通信时,接收到的数据是以字节流的形式传输的,因此需要将接收到的字节流转换为字符串,再解析字符串中的XML数据。 以下是一个示例代码,演示了如何使用C#Socket进行TCP通信,并接收并解析XML数据: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Xml; class TcpListenerExample { public static void Main() { TcpListener server = null; try { // Set the TcpListener on port 13000. Int32 port = 13000; IPAddress localAddr = IPAddress.Parse("127.0.0.1"); // TcpListener server = new TcpListener(port); server = new TcpListener(localAddr, port); // Start listening for client requests. server.Start(); // Buffer for reading data Byte[] bytes = new Byte[256]; String data = null; // Enter the listening loop. while (true) { Console.Write("Waiting for a connection... "); // Perform a blocking call to accept requests. // You could also use server.AcceptSocket() here. TcpClient client = server.AcceptTcpClient(); Console.WriteLine("Connected!"); data = null; // Get a stream object for reading and writing NetworkStream stream = client.GetStream(); int i; // Loop to receive all the data sent by the client. while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) { // Translate data bytes to a ASCII string. data = Encoding.ASCII.GetString(bytes, 0, i); Console.WriteLine("Received: {0}", data); // Parse the XML data XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(data); // Do something with the XML data XmlNodeList nodes = xmlDoc.GetElementsByTagName("message"); foreach (XmlNode node in nodes) { Console.WriteLine("Message: {0}", node.InnerText); } // Send a response back to the client. byte[] msg = Encoding.ASCII.GetBytes("Message received."); stream.Write(msg, 0, msg.Length); Console.WriteLine("Sent: {0}", "Message received."); } // Shutdown and end connection client.Close(); } } catch (SocketException e) { Console.WriteLine("SocketException: {0}", e); } finally { // Stop listening for new clients. server.Stop(); } Console.WriteLine("\nHit enter to continue..."); Console.Read(); } } ``` 在上面的代码中,当接收到数据时,我们将其转换为字符串,并使用XmlDocument对象来解析XML数据。在本例中,我们假设XML数据包含一个名为“message”的元素,我们使用GetElementsByTagName方法获取所有名为“message”的元素,并遍历它们以输出其InnerText属性。你可以根据实际情况修改代码以适应你的XML数据结构。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值