Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#异步聊天服务器_C#_Sockets_Asynchronous_Server_Chat - Fatal编程技术网

C#异步聊天服务器

C#异步聊天服务器,c#,sockets,asynchronous,server,chat,C#,Sockets,Asynchronous,Server,Chat,我正在尝试构建一个异步聊天服务器,这就是我目前得到的: 服务器 using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; public class StateObject { public Socket workSocket = null; public const int BufferSize = 1024; public b

我正在尝试构建一个异步聊天服务器,这就是我目前得到的:

服务器

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

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

public class AsynchronousSocketListener
{
public static ManualResetEvent allDone = new ManualResetEvent(false);

public AsynchronousSocketListener()
{
}

public static void StartListening()
{
    byte[] bytes = new Byte[1024];
    IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
    Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);

    try
    {
        listener.Bind(localEndPoint);
        listener.Listen(100);

        while (true)
        {
            allDone.Reset();
            Console.WriteLine("Waiting for a connection...");
            listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
            allDone.WaitOne();
        }

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

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

}

public static void AcceptCallback(IAsyncResult ar)
{
    allDone.Set();
    Socket listener = (Socket)ar.AsyncState;
    Socket handler = listener.EndAccept(ar);
    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;
    StateObject state = (StateObject)ar.AsyncState;
    Socket handler = state.workSocket;
    int bytesRead = handler.EndReceive(ar);

    if (bytesRead > 0)
    {
        state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
        content = state.sb.ToString();
        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, StateObject.BufferSize, 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 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;
}
}
使用系统;
Net系统;
使用System.Net.Sockets;
使用系统文本;
使用系统线程;
公共类状态对象
{
公共套接字工作组=null;
public const int BufferSize=1024;
公共字节[]缓冲区=新字节[BufferSize];
公共StringBuilder sb=新StringBuilder();
}
公共类异步SocketListener
{
public static ManualResetEvent allDone=新的ManualResetEvent(false);
公共异步SocketListener()
{
}
公共静态侦听()
{
字节[]字节=新字节[1024];
IPAddress=IPAddress.Parse(“127.0.0.1”);
IPEndPoint localEndPoint=新IPEndPoint(ipAddress,11000);
套接字侦听器=新套接字(AddressFamily.InterNetwork、SocketType.Stream、ProtocolType.Tcp);
尝试
{
Bind(localEndPoint);
听,听(100);
while(true)
{
全部完成。重置();
Console.WriteLine(“等待连接…”);
beginacept(新的异步回调(AcceptCallback),listener);
全部完成。WaitOne();
}
}
捕获(例外e)
{
Console.WriteLine(如ToString());
}
Console.WriteLine(“\n按ENTER继续…”);
Console.Read();
}
公共静态无效接受回调(IAsyncResult ar)
{
allDone.Set();
套接字侦听器=(套接字)ar.AsyncState;
套接字处理程序=listener.EndAccept(ar);
StateObject状态=新的StateObject();
state.workSocket=处理程序;
BeginReceive(state.buffer,0,StateObject.BufferSize,0,新异步回调(ReadCallback),state);
}
公共静态void ReadCallback(IAsyncResult ar)
{
String content=String.Empty;
StateObject状态=(StateObject)ar.AsyncState;
套接字处理程序=state.workSocket;
int bytesRead=handler.EndReceive(ar);
如果(字节读取>0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
content=state.sb.ToString();
if(content.IndexOf(“”>-1)
{ 
WriteLine(“从套接字读取{0}字节。\n数据:{1}”,content.Length,content);
发送(处理程序、内容);
}
其他的
{
BeginReceive(state.buffer,0,StateObject.BufferSize,0,新异步回调(ReadCallback),state);
}
}
}
私有静态void发送(套接字处理程序、字符串数据)
{
byte[]byteData=Encoding.ASCII.GetBytes(数据);
BeginSend(byteData,0,byteData.Length,0,新异步回调(SendCallback),handler);
}
私有静态void SendCallback(IAsyncResult ar)
{
尝试
{
套接字处理程序=(套接字)ar.AsyncState;
int bytesSent=handler.EndSend(ar);
WriteLine(“发送{0}字节到客户端。”,bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
捕获(例外e)
{
Console.WriteLine(如ToString());
}
}
公共静态int Main(字符串[]args)
{
惊人的倾听();
返回0;
}
}
客户

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

public class StateObject
{
    public Socket workSocket = null;
    public const int BufferSize = 256;
    public byte[] buffer = new byte[BufferSize];
    public StringBuilder sb = new StringBuilder();
}

public class AsynchronousClient
{
    private const int port = 11000;
    private static ManualResetEvent connectDone =new ManualResetEvent(false);
    private static ManualResetEvent sendDone =new ManualResetEvent(false);
    private static ManualResetEvent receiveDone =new ManualResetEvent(false);
    private static String response = String.Empty;
    static String username = "";
    static int a = 1;

private static void StartClient()
{
    try
    { 
        Console.WriteLine("Username: ");
        username = Console.ReadLine();

        while (a == 1)
        {
            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();

            Console.WriteLine("Receiver: ");
            String receiver = Console.ReadLine();
            Console.WriteLine("Message: ");
            String message = Console.ReadLine();

            String Message = username + "[" + receiver + "[" + message + "<EOF>";
            Send(client, Message);
            sendDone.WaitOne();
            Receive(client);
            receiveDone.WaitOne();
            Console.WriteLine("Response received : {0}", response);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void ConnectCallback(IAsyncResult ar)
{
    try
    {
        Socket client = (Socket)ar.AsyncState;
        client.EndConnect(ar);
        connectDone.Set();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void Receive(Socket client)
{
    try
    {
        StateObject state = new StateObject();
        state.workSocket = client;
        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReceiveCallback), state);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void ReceiveCallback(IAsyncResult ar)
{
    try
    {
        StateObject state = (StateObject)ar.AsyncState;
        Socket client = state.workSocket;
        int bytesRead = client.EndReceive(ar);

        if (bytesRead > 0)
        {
            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReceiveCallback), state);
        }
        else
        {
            if (state.sb.Length > 1)
            {
                response = state.sb.ToString();
            }
            receiveDone.Set();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void Send(Socket client, String data)
{
    byte[] byteData = Encoding.ASCII.GetBytes(data);
    client.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), client);
}

private static void SendCallback(IAsyncResult ar)
{
    try
    {
        Socket client = (Socket)ar.AsyncState;
        int bytesSent = client.EndSend(ar);
        Console.WriteLine("Sent {0} bytes to server.", bytesSent);
        sendDone.Set();
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

public static int Main(String[] args)
{
    StartClient();
    return 0;
}
}
使用系统;
Net系统;
使用System.Net.Sockets;
使用系统线程;
使用系统文本;
公共类状态对象
{
公共套接字工作组=null;
public const int BufferSize=256;
公共字节[]缓冲区=新字节[BufferSize];
公共StringBuilder sb=新StringBuilder();
}
公共类异步客户端
{
专用常量int端口=11000;
专用静态手动复位事件连接完成=新手动复位事件(错误);
专用静态手动复位事件sendDone=新手动复位事件(false);
private static ManualResetEvent receiveDone=新的ManualResetEvent(错误);
私有静态字符串响应=String.Empty;
静态字符串username=“”;
静态int a=1;
私有静态void StartClient()
{
尝试
{ 
Console.WriteLine(“用户名:”);
username=Console.ReadLine();
while(a==1)
{
IPAddress=IPAddress.Parse(“127.0.0.1”);
IPEndPoint remoteEP=新IPEndPoint(ipAddress,端口);
Socket client=新套接字(AddressFamily.InterNetwork、SocketType.Stream、ProtocolType.Tcp);
BeginConnect(remoteEP,新的异步回调(ConnectCallback),client);
connectDone.WaitOne();
控制台。写入线(“接收方:”);
String receiver=Console.ReadLine();
Console.WriteLine(“消息:”);
String message=Console.ReadLine();
字符串消息=用户名+“[”+接收者+“[”+消息+”;
发送(客户端、消息);
sendDone.WaitOne();
接收(客户);
receiveDone.WaitOne();
WriteLine(“收到的响应:{0}”,响应);
}
}
捕获(例外e)
{
Console.WriteLine(如ToString());
}
}
专用静态无效连接回调(IAsyncResult ar)
{
尝试
{
套接字客户端=(套接字)ar.AsyncState;
客户端.EndConnect(ar);
connectDone.Set();
}
捕获(例外e)
{
Console.WriteLine(如ToString());
}
}
私有静态void接收(套接字客户端)
{
尝试
{
StateObject状态=新的StateObject();
state.workSocket=客户端;
client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,新异步回调(ReceiveCallback),state);
}
捕获(例外e)
{
Console.WriteLine(如ToString());
}
}
私有静态void ReceiveCallback(IAsyncResult ar)
{
尝试
{
StateObject状态=(StateObject)ar.AsyncState;
套接字客户端=state.workSocket;
int bytesRead=client.EndReceive(ar);
如果(字节读取>0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,新异步回调(ReceiveCallback),state);
}
Socket handler = (Socket) ar.AsyncState;
handler.Shutdown(SocketShutdown.Both);
handler.Close();