Witam serdecznie. Postanowiłem napisać mały serwer, lecz pojawiło się pytanie, na które nie znalazłem odpowiedzi, a mianowicie jeśli mam Socket, który słucha (listen), to jeśli jakiś client do niego wyśle dane, to w jaki sposób mam ją odebrać. Oto kod:
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Text;
namespace Server {
class Program {
static Thread acceptingThread;
static Thread receiveThread;
private static Socket listener;
private static int port;
private static int slots;
private static int clientsConnected;
private static bool running = false;
private static string version = "1.0";
private byte[] buffer = new byte[1024];
private static Dictionary<Socket, string> clients = new Dictionary<Socket, string> (slots);
private static List<Request> requestsToSend = new List<Request> ();
static void Init () {
Console.WriteLine ("Starting server...");
listener = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine ("Binding server...");
listener.Bind (new IPEndPoint (IPAddress.Parse ("127.0.0.1"), port));
Console.WriteLine ("Server starts listening...");
listener.Listen (0);
running = true;
Console.Clear ();
Console.WriteLine ("Server is running. Start time: " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString());
}
static void Run () {
acceptingThread = new Thread (AcceptingLoop);
}
internal static void AcceptingLoop () {
while (running) {
Socket temp = listener.Accept ();
byte[] buffer = new byte[1024];
int length = temp.Receive (buffer, SocketFlags.None);
if (Encoding.UTF8.GetString (buffer, 0, length) != version) {
temp.Disconnect (false);
return;
}
length = temp.Receive (buffer, SocketFlags.None);
string dataString = Encoding.UTF8.GetString (buffer, 0, length);
clients.Add (temp, dataString);
}
}
internal static void ReceivingLoop () {
while (running) {
//Jak tutaj pobrać dane?
}
}
static void Exit () { }
static void Main (string[] args) {
Init ();
Run ();
}
}
}