Created
May 22, 2017 17:57
-
-
Save Pan-Maciek/fa15a22205626fa2ffe7e8ef2b9c2672 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Server : IDisposable { | |
private static JavaScriptSerializer JSON = new JavaScriptSerializer(); | |
class Message { | |
public string Content; | |
} | |
class Client : IDisposable { | |
Socket socket; | |
StringBuilder sb = new StringBuilder(); | |
Server server; | |
const int BufferSize = 1024; | |
byte[] Buffer = new byte[BufferSize]; | |
private void Recive() { | |
socket.BeginReceive(Buffer, 0, BufferSize, SocketFlags.None, result => { | |
try { | |
int bytesRead = socket.EndReceive(result); | |
if (bytesRead > 0) { | |
sb.Append(UTF8.GetString(Buffer, 0, bytesRead)); | |
var content = sb.ToString(); | |
if (content.IndexOf("\r\n\r\n") != -1) { | |
sb.Length -= 2; | |
MessageHandeler(sb.ToString()); | |
Buffer = new byte[BufferSize]; | |
sb.Clear(); | |
} | |
} | |
Recive(); | |
} catch (Exception) { | |
Console.WriteLine("wow coś sie popsuło"); | |
} | |
}, null); | |
} | |
private void MessageHandeler(string _message) { | |
var message = JSON.Deserialize<Message>(_message); | |
onMessage?.Invoke(this, message); | |
Console.WriteLine(message.Content); | |
} | |
public Client(Socket socket, Server s) { | |
this.socket = socket; | |
server = s; | |
Recive(); | |
} | |
public void Send(string message) { | |
var bytes = UTF8.GetBytes(message); | |
socket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, result => { | |
int bytesSend = socket.EndSend(result); | |
Console.WriteLine($"send {}"); | |
}, null); | |
} | |
public event EventHandler<Message> onMessage; | |
public void Dispose() { | |
socket.Shutdown(SocketShutdown.Both); | |
socket.Close(); | |
server.Clients.Remove(this); | |
} | |
} | |
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); | |
LinkedList<Client> Clients = new LinkedList<Client>(); | |
public void Listen(int port) { | |
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, port); | |
socket.Bind(endPoint); | |
socket.Listen(100); | |
AcceptConnections(); | |
Console.WriteLine($"Server listening at port: {port}"); | |
} | |
private void AcceptConnections() { | |
socket.BeginAccept(result => { | |
AcceptConnections(); | |
Socket handler = socket.EndAccept(result); | |
Clients.AddFirst(new Client(handler, this)); | |
}, null); | |
} | |
public void Dispose() { | |
throw new NotImplementedException(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment