简体   繁体   中英

Single server/multiple clients in C#

I am new to C# programming. So far, I have a single server/single client, but I need to turn it into a single server/multiple client. Here is my code:

TankServer

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

    namespace TankServer
    {
      class Program
    {
        static Socket sck;
        static Socket acc;
        static int port = 1700;
        static IPAddress ip;
        static Thread rec;
        static string name;

        static string GetIp()
        {
            string strHostName = System.Net.Dns.GetHostName();
            IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
            IPAddress[] addr = ipEntry.AddressList;
            return addr[addr.Length - 1].ToString();
        }


        static void recV()
        {
            while (true)
            {
                Thread.Sleep(500);
                byte[] Buffer = new byte[255];
                int rec = acc.Receive(Buffer, 0, Buffer.Length, 0);
                Array.Resize(ref Buffer, rec);
                Console.WriteLine(Encoding.Default.GetString(Buffer));
            }
        }

        static void Main(string[] args)
        {
            rec = new Thread(recV);
            Console.WriteLine("Your Local Ip is : " + GetIp());
            Console.WriteLine("Please enter yout name");
            name = Console.ReadLine();
            Console.WriteLine("Please Enter Your Host Port");
            string inputPort = Console.ReadLine();
            try { port = Convert.ToInt32(inputPort); }
            catch { port = 1700; }

            ip=IPAddress.Parse(GetIp());
            sck= new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            sck.Bind(new IPEndPoint(ip, port));
            sck.Listen(0);
            acc=sck.Accept();
            rec.Start();

            while(true){
                byte[] sdata=Encoding.ASCII.GetBytes("<"+name+">"+Console.ReadLine());
                acc.Send(sdata,0,sdata.Length,0);
            }
        }
    }
}

TankClient

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

 namespace TankClient
 {
  class Program
  {
    static string name = "";
    static int port = 1700;
    static IPAddress ip;
    static Socket sck;
    static Thread rec;

    static void recV()
    {
        while (true)
        {
            Thread.Sleep(500);
            byte[] Buffer = new byte[255];
            int rec = sck.Receive(Buffer, 0, Buffer.Length, 0);
            Array.Resize(ref Buffer, rec);
            Console.WriteLine(Encoding.Default.GetString(Buffer));
        }
    }

    static void Main(string[] args)
    {

        rec = new Thread(recV);
        while(true){
        Console.WriteLine("Please enter your name");
        name = Console.ReadLine();
        Console.WriteLine("Please enter the ip of the server");
        ip = IPAddress.Parse(Console.ReadLine());
        Console.WriteLine("Please Enter The Port");
        string inputPort = Console.ReadLine();
        try { port = Convert.ToInt32(inputPort); }
        catch { port = 1700; }

        sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        sck.Connect(new IPEndPoint(ip, port));
        rec.Start();
        byte[] conmsg = Encoding.Default.GetBytes("<" + name + ">" + "Connected");
        sck.Send(conmsg, 0, conmsg.Length, 0);

        while (sck.Connected)
        {
            byte[] sdata = Encoding.Default.GetBytes("<" + name + ">"+Console.ReadLine());
            sck.Send(sdata, 0, sdata.Length, 0);
        }
    }
  }
 }
  }

I searched on the internet, but I really don't understand how to do it.

You need use threads to handle clients on server side.

Here you can find tutorial how to make server on threads

http://csharp.net-informations.com/communications/csharp-multi-threaded-server-socket.htm

It's very good.

Basicly. Server is listening in while(true) loop when connects Server creates new thread to handle communication with the client.

If you are beginner my good adivce is to use Async functions to recieve/send data to prevent UI stop responding. Function like BeginConnect, EndConnect, BeginRecieve, EndRecieve. etc.

Communicating through sockets - for an example you can check:

http://ludwigstuyck.wordpress.com/2012/09/21/communicating-through-sockets/

It's like a quick start with code samples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM