Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- namespace Server
- {
- class Server
- {
- bool running = true;
- int clients = 0;
- public void Start()
- {
- //Accept connections
- Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- IPEndPoint endpoint = new IPEndPoint(new IPAddress(0x0100007f), 5678); //127.0.0.1
- socket.Bind(endpoint);
- socket.Listen(10);
- while (running)
- {
- Socket client = socket.Accept();
- Thread processClient = new Thread(new ParameterizedThreadStart(HandleClient));
- var info = new ClientInfo()
- {
- Socket = client,
- ID = ++clients
- };
- processClient.Start(info);
- }
- }
- public void HandleClient(object client)
- {
- Socket socket = ((ClientInfo)client).Socket;
- int id = ((ClientInfo)client).ID;
- Console.WriteLine("Client connected");
- byte[] buffer = new byte[1024];
- int bytesRead;
- bool talking = true;
- while (talking)
- {
- bytesRead = 0;
- try
- {
- bytesRead = socket.Receive(buffer);
- }
- catch
- {
- break;
- }
- if (bytesRead == 0) {
- break;
- }
- string message = UTF8Encoding.UTF8.GetString(buffer, 0, bytesRead);
- if (message == "exit") break;
- Console.WriteLine("Got Message {0} from #{1}", message, id);
- }
- socket.Close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement