c#异步socket

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace server
{
    class Program
    {
        //服务端buffer为4字节
        static byte[] buffer = new byte[1024];
        static string Json = "";
        static int connt = 0;
        static void Main(string[] args)
        {
            Console.WriteLine("[Server]");
            try
            {
                Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                socketServer.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4444));
                socketServer.Listen(int.MaxValue);
                Console.WriteLine("服务端已启动,等待连接...");
                //接收连接
                Socket ts = socketServer.Accept();
                Console.WriteLine("客户端已连接");

                //开始异步接收
                ts.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), ts);
                Console.WriteLine(Json);
                Console.WriteLine(Convert.ToString(connt));
                Console.ReadKey();
            }
            catch (Exception e)
            {
                
                Console.WriteLine(e.Message);
            }
        }

        static void ReceiveCallback(IAsyncResult result)
        {
            Socket ts = (Socket)result.AsyncState;
            ts.EndReceive(result);
            result.AsyncWaitHandle.Close();
            Console.WriteLine("收到消息");
            Json += Encoding.ASCII.GetString(buffer);
            //清空数据,重新开始异步接收
            buffer = new byte[buffer.Length];
            connt += 1;
            ts.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), ts);
        }
    }
}

client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace client
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("[Client]");
            try
            {
                Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socketClient.Connect(IPAddress.Parse("127.0.0.1"), 4444);
                Console.WriteLine("发送消息:");
                 System.IO.StreamReader sr = new System.IO.StreamReader(@"C:\1.txt");
                 string sendStr = sr.ReadLine();
                //获取发送内容
                while (true)
                {
                    Console.WriteLine("发送消息:");
                    //同步发送数据
                    socketClient.Send(Encoding.ASCII.GetBytes(sendStr));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine("按任意键退出");
                Console.ReadKey();
            }
        }
    }
}


你可能感兴趣的:(socket,异步,c#,编程,读书笔记)