0
点赞
收藏
分享

微信扫一扫

.Net Sockets通讯

骨灰级搬砖工 2024-03-08 阅读 10

.Net Sockets通讯

在.NET框架中,Sockets编程是一种底层的网络通信方式,它允许开发者在不同的机器和应用之间建立直接的通信渠道。通过Sockets,我们可以实现各种复杂的网络应用,包括聊天室、文件传输、网络游戏等。

下面,我们将通过实战的方式,介绍如何在.NET中使用Sockets进行通信。

一、Socket的基本概念

在.NET中,Socket类位于System.Net.Sockets命名空间下。Socket类提供了网络通信的基础功能,包括创建套接字、绑定地址、监听连接、发送和接收数据等。

二、创建Socket服务器

首先,我们需要创建一个Socket服务器来监听客户端的连接请求。以下是一个简单的Socket服务器示例:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

class SocketServer
{
    static void Main()
    {
        IPAddress ip = IPAddress.Parse("127.0.0.1");
        TcpListener listener = new TcpListener(ip, 8000);
        listener.Start();

        Console.WriteLine("Server started...");
        while (true)
        {
            TcpClient client = listener.AcceptTcpClient();
            Thread thread = new Thread(new ParameterizedThreadStart(HandleClientComm));
            thread.Start(client);
        }
    }

    static void HandleClientComm(object client)
    {
        TcpClient tcpClient = (TcpClient)client;
        NetworkStream clientStream = tcpClient.GetStream();

        byte[] message = new byte[4096];
        int bytesRead;

        while (true)
        {
            bytesRead = 0;

            try
            {
                // Blocks until a client sends a message
                bytesRead = clientStream.Read(message, 0, 4096);
            }
            catch
            {
                // A socket error has occured
                break;
            }

            if (bytesRead == 0)
            {
                // The client has disconnected from the server
                break;
            }

            // Message has successfully been received
            ASCIIEncoding encoder = new ASCIIEncoding();
            string s = encoder.GetString(message, 0, bytesRead);
            Console.WriteLine("Received: {0}", s);
        }

        tcpClient.Close();
    }
}

在这个示例中,我们首先创建了一个TcpListener对象,并指定了要监听的IP地址和端口号。然后,我们启动监听器,并进入一个无限循环,等待客户端的连接请求。每当有客户端连接时,我们就创建一个新的线程来处理与该客户端的通信,这样服务器就可以同时处理多个客户端的请求。

三、创建Socket客户端

接下来,我们创建一个Socket客户端来连接服务器并发送数据:

using System;
using System.Net.Sockets;
using System.Text;

class SocketClient
{
    static void Main(string[] args)
    {
        TcpClient client = new TcpClient("127.0.0.1", 8000);
        Console.WriteLine("Connected to the server.");

        NetworkStream stream = client.GetStream();

        Console.Write("Enter the string to be transmitted : ");
        string userInput = Console.ReadLine();

        Byte[] data = System.Text.Encoding.ASCII.GetBytes(userInput);

        stream.Write(data, 0, data.Length);
        Console.WriteLine("Sent: {0}", userInput);

        data = new Byte[256];

        String responseData = String.Empty;

        Int32 bytes = stream.Read(data, 0, data.Length);
        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
        Console.WriteLine("Received: {0}", responseData);

        stream.Close();
        client.Close();
    }
}

在这个示例中,我们创建了一个TcpClient对象,并指定了要连接的服务器的IP地址和端口号。然后,我们获取到与服务器通信的网络流,从控制台读取用户输入的数据,并将其转换为字节数组发送给服务器。接着,我们读取服务器返回的数据,并将其转换为字符串打印出来。最后,我们关闭网络流和TcpClient对象。

四、总结

以上就是一个简单的.NET Sockets通讯实战示例。通过创建Socket服务器和客户端,我们可以实现基本的网络通信功能。在实际开发中,我们可能还需要处理更复杂的情况,比如错误

举报

相关推荐

0 条评论