在同一个控制台中接收和发送文本,UDP Socket

时间:2018-04-12 21:02:24

标签: c# sockets console udp

我试图在同一个控制台中发送和接收文本,但我无法将server.cs实现到client.cs,当我独立运行它们时,只有客户端发送和服务器接收,但我想发送和接收对于他们两个人的信息,我该怎么办呢?

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

namespace ConsoleApp21
{
    class Program
    {
        static void Main(string[] args)
        {



            Console.WriteLine("Server waiting for connect");
            UdpClient client = new UdpClient(5555);

            cli();
            sv();

            void cli()
            {

                Console.Write(">");
                string input = Console.ReadLine();
                if (input != null)
                {
                    byte[] bytesent = Encoding.ASCII.GetBytes(input);

                    client.Send(bytesent, bytesent.Length);
                    client.Close();
                    Console.WriteLine("Successfully message sent");

                    Console.ReadLine();
                }

            }
            void sv()
            {
                IPEndPoint remoteip = new IPEndPoint(IPAddress.Any, 5555);


                byte[] receviedbyte = client.Receive(ref remoteip);

                if (remoteip != null)
                {
                    string message = Encoding.ASCII.GetString(receviedbyte);
                    Console.WriteLine(message);

                }
                else
                {
                    Console.WriteLine("empty mesaage has been received");
                }
                Console.ReadLine();







            }
        }
    }
}

这是服务器:

{{1}}

1 个答案:

答案 0 :(得分:0)

这是您使用它的方式:

服务器

public class Server
{
    private readonly UdpClient _listener;
    public Server(int port)
    {
        _listener = new UdpClient(port);
    }
    public void Run()
    {
        try
        {
            _listener.BeginReceive(new AsyncCallback(ProcessResult), null);
            Console.WriteLine("[SERVER]: Started");
        }
        catch (Exception e)
        {
            Console.WriteLine("[SERVER][ERR]: {0}", e);
            Console.WriteLine("[SERVER][ERR]: Stopping...");
        }
    }

    private void ProcessResult(IAsyncResult result)
    {
        var remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
        var received = _listener.EndReceive(result, ref remoteIpEndPoint);

        try
        {
            ProcessReceived(received, remoteIpEndPoint);
        }
        catch (Exception e)
        {
            Console.WriteLine("[SERVER][ERR]: Error on processing: {0}", e);
        }

        _listener.BeginReceive(new AsyncCallback(ProcessResult), null);
    }

    private void ProcessReceived(byte[] received, IPEndPoint sender)
    {
        Console.WriteLine("[SERVER]: Receieved '{0}'. Sending 'Thank you' to {1}", Encoding.ASCII.GetString(received), sender);
        var reply = Encoding.ASCII.GetBytes("Thank you");
        _listener.SendAsync(reply, reply.Length, sender);
    }
}

<强>客户端:

class Client
{

    private readonly UdpClient _serverClient;
    public Client(string host, int port)
    {
        _serverClient = new UdpClient(host,port);
    }
    public void Run()
    {
        //Here we tell client to receive callbacks from server
        try
        {
            _serverClient.BeginReceive(new AsyncCallback(ProcessCallback), null);
        }
        catch (Exception e)
        {
            Console.WriteLine("[CLIENT][ERR]: {0}", e);
            Console.WriteLine("[CLIENT][ERR]: Stopping...");
            return;
        }
        Console.WriteLine("[CLIENT]: Started");

        //Here we making some "client" routine - just writting messages and sending them to server
        while (true)
        {
            string input = Console.ReadLine();
            if (input != null)
            {
                if (input == "stop")
                {
                    break;
                }
                byte[] bytesent = Encoding.ASCII.GetBytes(input);
                _serverClient.Send(bytesent, bytesent.Length);
                Console.WriteLine("[CLIENT]: Sent '{0}'", input);
            }
        }
    }

    private void ProcessCallback(IAsyncResult result)
    {
        var remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
        var received = _serverClient.EndReceive(result, ref remoteIpEndPoint);

        try
        {
            ProcessReceived(received, remoteIpEndPoint);
        }
        catch (Exception e)
        {
            Console.WriteLine("[CLIENT][ERR]: Error on processing: {0}", e);
        }

        _serverClient.BeginReceive(new AsyncCallback(ProcessCallback), null);
    }

    private void ProcessReceived(byte[] received, IPEndPoint remoteIpEndPoint)
    {
        Console.WriteLine("[CLIENT]: Receieved '{0}' from server.", Encoding.ASCII.GetString(received));
    }
}

<强>启动

class Program
{
    static void Main(string[] args)
    {
        var server = new Server(5555); //will listen on port 5555
        server.Run();
        var client = new Client("127.0.0.1", 5555); //will try to connect to 127.0.0.1:5555 which is our server, and receive callbacks on "some" port
        client.Run();
    }
}