DotNet:Socket Server 异步套接字服务端实现

转载 2017年04月18日 17:20:05

异步服务器套接字示例

From https://msdn.microsoft.com/zh-cn/library/fx6588te(v=vs.110).aspx

下面的示例程序创建接收来自客户端的连接请求的服务器。 服务器以异步套接字生成,因此,服务器应用程序的执行不会挂起,它在等待从客户端时的连接。 应用程序收到来自客户端的字符串,在控制台上显示字符串,然后回显该字符串返回给客户端。 从客户端的字符串必须包含字符串“”用于通知消息的结尾。
C#

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

// State object for reading client data asynchronously
public class StateObject {
    // Client  socket.
    public Socket workSocket = null;
    // Size of receive buffer.
    public const int BufferSize = 1024;
    // Receive buffer.
    public byte[] buffer = new byte[BufferSize];
// Received data string.
    public StringBuilder sb = new StringBuilder();  
}

public class AsynchronousSocketListener {
    // Thread signal.
    public static ManualResetEvent allDone = new ManualResetEvent(false);

    public AsynchronousSocketListener() {
    }

    public static void StartListening() {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        // Establish the local endpoint for the socket.
        // The DNS name of the computer
        // running the listener is "host.contoso.com".
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp );

        // Bind the socket to the local endpoint and listen for incoming connections.
        try {
            listener.Bind(localEndPoint);
            listener.Listen(100);

            while (true) {
                // Set the event to nonsignaled state.
                allDone.Reset();

                // Start an asynchronous socket to listen for connections.
                Console.WriteLine("Waiting for a connection...");
                listener.BeginAccept( 
                    new AsyncCallback(AcceptCallback),
                    listener );

                // Wait until a connection is made before continuing.
                allDone.WaitOne();
            }

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

        Console.WriteLine("\nPress ENTER to continue...");
        Console.Read();

    }

    public static void AcceptCallback(IAsyncResult ar) {
        // Signal the main thread to continue.
        allDone.Set();

        // Get the socket that handles the client request.
        Socket listener = (Socket) ar.AsyncState;
        Socket handler = listener.EndAccept(ar);

        // Create the state object.
        StateObject state = new StateObject();
        state.workSocket = handler;
        handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
            new AsyncCallback(ReadCallback), state);
    }

    public static void ReadCallback(IAsyncResult ar) {
        String content = String.Empty;

        // Retrieve the state object and the handler socket
        // from the asynchronous state object.
        StateObject state = (StateObject) ar.AsyncState;
        Socket handler = state.workSocket;

        // Read data from the client socket. 
        int bytesRead = handler.EndReceive(ar);

        if (bytesRead > 0) {
            // There  might be more data, so store the data received so far.
            state.sb.Append(Encoding.ASCII.GetString(
                state.buffer,0,bytesRead));

            // Check for end-of-file tag. If it is not there, read 
            // more data.
            content = state.sb.ToString();
            if (content.IndexOf("<EOF>") > -1) {
                // All the data has been read from the 
                // client. Display it on the console.
                Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
                    content.Length, content );
                // Echo the data back to the client.
                Send(handler, content);
            } else {
                // Not all data received. Get more.
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReadCallback), state);
            }
        }
    }

    private static void Send(Socket handler, String data) {
        // Convert the string data to byte data using ASCII encoding.
        byte[] byteData = Encoding.ASCII.GetBytes(data);

        // Begin sending the data to the remote device.
        handler.BeginSend(byteData, 0, byteData.Length, 0,
            new AsyncCallback(SendCallback), handler);
    }

    private static void SendCallback(IAsyncResult ar) {
        try {
            // Retrieve the socket from the state object.
            Socket handler = (Socket) ar.AsyncState;

            // Complete sending the data to the remote device.
            int bytesSent = handler.EndSend(ar);
            Console.WriteLine("Sent {0} bytes to client.", bytesSent);

            handler.Shutdown(SocketShutdown.Both);
            handler.Close();

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


    public static int Main(String[] args) {
        StartListening();
        return 0;
    }
}

相关文章推荐

网络编程二(套接字Socket、客户端和服务端通信问题)

在客户机/服务器工作模式中,在Server端,要准备接受多个Client端计算机的通信。为此,除用IP地址标识Internet上的计算机之外,另还引入端口号,用端口号标识正在Server端后台服务的线...

net Winform socket 套接字聊天室客户端和服务端 源码

///-------------------------------------- 客户端----------------------------------   using System; ...

【网络编程】使用流式套接字实现简单的客户端/服务端通信过程

实验要求: 1. 熟悉流式套接字socket函数的使用方法,包括建立连接、数据发送/接收和关闭连接等; 2. 客户端可向服务端发送任意字符串,服务端在接收到该字符串后,回送给客户端; 3. 服务...

流式套接字实现简单的客户端/服务端通信过程

流式套接字实现简单的客户端/服务端通信过程一、 实验内容 熟悉流式套接字socket函数的使用方法,包括建立连接、数据发送/接收和关闭连接等; 客户端可向服务端发送任意字符串,服务端在接收到该字 符...

c#(Socket)异步套接字代码示例

  • 2009年03月11日 10:43
  • 33KB
  • 下载

套接字之客户端和服务端的一次通信

套接字之练习1

详解C语言开发unix/Linux下安全套接字(SSL)的TCP服务端程序

本文详细说明了用C语言开发UNIX/Linux下安全套接字(TCP SSL) 的服务端程序,采用IO多路复用,单进程单线程,自定义并实现 缓存,链表等数据结构,代码由本人亲自编写,在IBM AIX...
  • qman007
  • qman007
  • 2011年02月25日 20:51
  • 2936

C#网络编程.2.套接字.TcpListener.TcpClient.服务端客户端通信

服务器端 using System; using System.Collections.Generic; using System.Linq; using System.Text; ...
  • valeb
  • valeb
  • 2012年04月26日 11:57
  • 859
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:DotNet:Socket Server 异步套接字服务端实现
举报原因:
原因补充:

(最多只允许输入30个字)