Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading.Tasks;
- namespace Server
- {
- public class Client
- {
- public event DataRecieved DataRecievedEvent;
- public delegate void DataRecieved(Byte[] data);
- public event ClientExited ClientExitedEvent;
- public delegate void ClientExited(Client client);
- private TcpClient client;
- public Client(TcpClient client_)
- {
- client = client_;
- client.GetStream().BeginRead(new byte[] { 0 }, 0, 0, Read, null);
- }
- private void Read(IAsyncResult ar)
- {
- try
- {
- NetworkStream NS = client.GetStream();
- byte[] buffer = new byte[1024];
- int bytesRead = NS.Read(buffer, 0, buffer.Length);
- //reads the buffer as a string for a command...
- string message = Encoding.UTF8.GetString(buffer);
- Console.WriteLine("data from client: " + message);
- String[] messageParts = message.Split(Shared.Separator);
- switch (messageParts[0])
- {
- case Shared.Message:
- Console.WriteLine(messageParts[1]);
- break;
- case Shared.FileRequest:
- Console.WriteLine("FileRecieve Message");
- break;
- }
- //calls read again...
- client.GetStream().BeginRead(new Byte[] { 0 }, 0, 0, new AsyncCallback(Read), null);
- }
- catch (Exception)
- {
- //error occured tell the server that this client exited...
- ClientExitedEvent(this);
- }
- }
- private void Write(Byte[] buffer)
- {
- if (client.GetStream().CanWrite)
- {
- client.GetStream().Write(buffer, 0, buffer.Length);
- }
- else
- {
- Console.WriteLine("Sorry. You cannot write to this NetworkStream.");
- }
- }
- public void SendMessage(string message)
- {
- //Shared.Message = "Message"
- //Shared.Separator = ((char)007);
- int length = message.Length + Shared.Message.Length + 1; //1 for the seperator character...
- byte[] buffer = new byte[length];
- byte[] msg = Encoding.UTF8.GetBytes(Shared.Message.ToCharArray());
- Array.Copy(msg, 0, buffer, 0, msg.Length);
- Array.Copy(new byte[] { Convert.ToByte(Shared.Separator) }, 0, buffer, Shared.Message.Length, 1);
- byte[] m = Encoding.UTF8.GetBytes(message);
- Array.Copy(m, 0, buffer, Shared.Message.Length + 1, m.Length );
- Console.WriteLine("Server sent message: " + message);
- Write(buffer);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment