C# Socket异步通信

本文介绍了一个使用 C# 实现的 Socket 异步通信示例程序。该程序通过异步方式监听并接收客户端连接请求,实现了服务器与客户端之间的简单消息交换。文章详细展示了如何设置 Socket 参数、处理连接请求及数据收发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

出自:http://www.cnblogs.com/llllll/archive/2009/05/13/1455703.html

今天研究了一下c#的socket 异步通信,参考了上面地址的博客自己实践了一下,做了一下测试,少许的改动了一下,原文是可以完美运行的,我真是稍微改动按照自己的理解

using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace socketAsyncCallback
{
    
    public class StateObject
    {
        public Socket WorkSocket = null;
        public const int  BufferSize = 1024;
        public byte[] buffer = new byte[BufferSize];
        public StringBuilder sb = new StringBuilder();
    }

    class Program
    {
        public static ManualResetEvent allDone = new ManualResetEvent(false);
        private static Socket listener;
        static void Main(string[] args)
        {
            StartListening();
            
        }

        public static void StartListening()
        {
            byte[] bytes = new byte[1024];
            
            IPAddress ipAddress = IPAddress.Parse("10.2.226.14");
            int port = 8885;
            IPEndPoint point = new IPEndPoint(ipAddress, port);

            listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            
            try
            {
                listener.Bind(point);
                listener.Listen(10);
                listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
                //这里本来是在这里启动一个begin的,我把他挪到了AcceptCallback方法里,这样就不用让主线程等待了
                /*
                while (true)
                {
                    allDone.Reset();

                    Console.WriteLine("Waiting fo a connection...");

                    listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);

                    allDone.WaitOne();
                }
                 */

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                
            }

            Console.WriteLine("\n Press Enter to continue");
            Console.Read();


        }

        public static void AcceptCallback(IAsyncResult ar)
        {
            listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
            Console.WriteLine("come in AcceptCallback");
            //allDone.Set();

            Socket myListener = (Socket) ar.AsyncState;
            Socket handler = myListener.EndAccept(ar);
            //握手,因为我这里用来连接进来的client 是用的同步的,所以一定要握手才可以,我连接就是用的前面的一篇 socketClient的文章
            handler.Send(Encoding.ASCII.GetBytes("server say hello"));
            //这里是申创造一个容器, 来传递socket
            StateObject state = new StateObject();
            state.WorkSocket = handler;
            handler.BeginReceive(state.buffer, 0, 1024, 0, new AsyncCallback(ReadCallback), state);
        }

        public static void ReadCallback(IAsyncResult ar)
        {
            
            string content = string.Empty;
            Console.WriteLine("READCALLBACK");
            StateObject state = (StateObject) ar.AsyncState;
            Socket handler = state.WorkSocket;
            int bytesRead = handler.EndReceive(ar);
            if (bytesRead > 0)
            {
                Console.WriteLine(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
                state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                content = state.sb.ToString();
                //Console.WriteLine(content);
                if (content.IndexOf("<EOF>") > -1)
                {
                    Console.WriteLine("Read {0} bytes from socket. \n Data: {1}",content.Length, content);
                    //给客户端响应,这里也可以注释掉,没有关系
                    Send(handler, content);
                }
                else
                {
                    handler.BeginReceive(state.buffer, 0, 1024, 0, new AsyncCallback(ReadCallback),
                        state);
                }
            }
        }

        private static void Send(Socket handler, string data)
        {
            byte[] byteData = Encoding.ASCII.GetBytes(data);

            handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
        }
        private static void SendCallback(IAsyncResult ar)
        {
            try
            {
                Socket handler = (Socket) ar.AsyncState;

                int bytesSend = handler.EndSend(ar);
                Console.WriteLine("Send {0} bytes to client.", bytesSend);
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();

            }
            catch (Exception e) 
            {
                Console.WriteLine(e.ToString());
               
            }
        }
    }
}






















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值