C# socket异步通信服务器和客户端

        本文章向大家介绍C# socket异步通信服务器和客户端,主要包括C# socket异步通信服务器和客户端使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

服务器代码

只要客户端连接进来就会接收到Server received data

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

class Program
{
    /// <summary>
    /// 缓存接受的数据的byte数组
    /// </summary>
    private static byte[] buffer = new byte[1024];

    private static int connectCount = 0;

    static void Main(string[] args)
    {
        //服务器需要绑定的IP和端口号
        IPEndPoint ed = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7788);
        //创建一个新的Tcp协议的Socket对象
        Socket Server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
        //服务器绑定该端口号和ip地址
        Server.Bind(ed);
        //设置该服务器至多只能监听十个客户端
        Server.Listen(10);
        //异步接收客户端
        Server.BeginAccept(new AsyncCallback(ClienAppcet), Server);
        Console.ReadKey();
    }


    private static void ClienAppcet(IAsyncResult ar)
    {
        //每当连接进来的客户端数量增加时链接数量自增1
        connectCount++;
        //服务端对象获取
        Socket ServerSocket = ar.AsyncState as Socket; 
        if (null != ServerSocket)
        {
            //得到接受进来的socket客户端
            Socket client = ServerSocket.EndAccept(ar);
            Console.WriteLine("第" + connectCount + "连接进来了");
            //开始异步接收客户端数据
            client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), client);
        }
        if (null != ServerSocket)
        {
            //通过递归来不停的接收客户端的连接
            ServerSocket.BeginAccept(new AsyncCallback(ClienAppcet), ServerSocket);
        }       
     }


    private static void ReceiveMessage(IAsyncResult ar)
    {
        Socket client = ar.AsyncState as Socket; //客户端对象
        if (client != null)
        {
            IPEndPoint clientipe = (IPEndPoint)client.RemoteEndPoint;
            try
            {
                int length = client.EndReceive(ar);

                string message = Encoding.UTF8.GetString(buffer, 0, length);
                WriteLine(clientipe + " :" + message, ConsoleColor.White);
                //服务器给客户端发送消息表示已经连接上
                client.Send(Encoding.UTF8.GetBytes("Server received data"));
                //通过递归不停的接收该客户端的消息
                client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), client);
            }
            catch (Exception)
            {
                //设置计数器
                connectCount--;
                //断开连接
                WriteLine(clientipe + " is disconnected,total connects " + (connectCount), ConsoleColor.Red);
            }
        }
    }


    public static void WriteLine(string str, ConsoleColor color)
    {
        Console.ForegroundColor = color;

        Console.WriteLine("[{0:MM-dd HH:mm:ss}] {1}", DateTime.Now, str);
    }
}

客户端代码

只要连接进来就能够打字给服务器发送消息

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


public class Program
{
    private static readonly byte[] Buffer = new byte[1024];

    private static void Main()
    {
        try
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //链接服务器的端口号和ip地址
            socket.Connect("127.0.0.1", 7788);
            WriteLine("Client: Connect to server success!", ConsoleColor.White);

            //开始异步接收服务器得到的消息
            socket.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);

            //只要客户端一直开着就能不停的往服务器发送消息
            while (true)
            {
                var message = Console.ReadLine();
                if (message != null)
                {
                    var outputBuffer = Encoding.UTF8.GetBytes(message);
                    //异步发送消息
                    socket.BeginSend(outputBuffer, 0, outputBuffer.Length, SocketFlags.None, null, null);
                }
            }
        }
        catch (Exception ex)
        {
            WriteLine("Client: Error " + ex.Message, ConsoleColor.Red);
        }
        finally
        {
            Console.Read();
        }
    }


    // 接收信息
    public static void ReceiveMessage(IAsyncResult ar)
    {
        try
        {
            var socket = ar.AsyncState as Socket;

            //方法参考:
            if (socket != null)
            {
                int length = socket.EndReceive(ar);
                string message = Encoding.ASCII.GetString(Buffer, 0, length);
                WriteLine(message, ConsoleColor.White);
            }

            //接收下一个消息
            if (socket != null)
            {
                socket.BeginReceive(Buffer, 0, Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket);
            }
        }
        catch (Exception ex)
        {
            WriteLine(ex.Message, ConsoleColor.Red);
        }
    }


    public static void WriteLine(string str, ConsoleColor color)
    {
        Console.ForegroundColor = color;
        Console.WriteLine("[{0:MM-dd HH:mm:ss}] {1}", DateTime.Now, str);
    }
}

http://www.manongjc.com/article/61596.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中进行socket网络编程可以实现一个服务器与多个客户端的通信,以下是一个简单的示例: 服务器端代码: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; namespace Server { class Program { static void Main(string[] args) { // 创建一个TCP/IP socket对象 Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 绑定IP地址和端口号 IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8888); listener.Bind(localEndPoint); // 开始监听连接请求 listener.Listen(10); Console.WriteLine("等待客户端连接..."); while (true) { // 接受来自客户端的连接请求 Socket handler = listener.Accept(); // 接收客户端发送的数据 byte[] buffer = new byte[1024]; int bytesRead = handler.Receive(buffer); string data = Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine($"接收到客户端数据:{data}"); // 向客户端发送响应数据 byte[] responseBytes = Encoding.ASCII.GetBytes("收到你的消息了!"); handler.Send(responseBytes); // 关闭连接 handler.Shutdown(SocketShutdown.Both); handler.Close(); } } } } ``` 客户端代码: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; namespace Client { class Program { static void Main(string[] args) { // 创建一个TCP/IP socket对象 Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 连接服务器 IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); IPEndPoint remoteEP = new IPEndPoint(ipAddress, 8888); sender.Connect(remoteEP); Console.WriteLine("连接服务器成功!"); // 向服务器发送数据 string message = "Hello, Server!"; byte[] bytes = Encoding.ASCII.GetBytes(message); sender.Send(bytes); // 接收服务器的响应数据 byte[] buffer = new byte[1024]; int bytesRead = sender.Receive(buffer); string response = Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine($"接收到服务器响应:{response}"); // 关闭连接 sender.Shutdown(SocketShutdown.Both); sender.Close(); Console.ReadKey(); } } } ``` 以上代码可以实现一个简单的服务器客户端通信,如果想实现多个客户端同时连接服务器,可以使用多线程或异步编程来处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值