C# Sockets and Multithreading - c#

I am trying to learn more about sockets and threading in c#.
I have come across a lot of good resources online to help get me started.
The program I made so far, is a simple "man-in-the-middle" application.
It's designed as the following: client <--> [application] <--> server
Given the following code, how can I prevent this thread from running at 100% CPU?
How can I have the thread wait and block for data and not exit when the client / server is idle?
while (true)
{
lock (ClientState)
{
checkConnectionStatus(client, server);
}
if (clientStream.CanRead && clientStream.DataAvailable)
{
Byte[] bytes = new Byte[(client.ReceiveBufferSize)];
IAsyncResult result = clientStream.BeginRead(bytes, 0, client.ReceiveBufferSize, null, null);
int size = clientStream.EndRead(result);
sendData(bytes, serverStream, size);
}
if (serverStream.CanRead && serverStream.DataAvailable)
{
Byte[] bytes = new byte[(server.ReceiveBufferSize)];
IAsyncResult result = serverStream.BeginRead(bytes, 0, server.ReceiveBufferSize, null, null);
int size = serverStream.EndRead(result);
sendData(bytes, clientStream, size);
}
}
EDIT: Decided to post the entire "Connection.cs" class for anyone interested. I'm a beginner programming, so I know there are some bad coding practices here. Basically this whole class is ran in another thread and should die when the connection (to either the client socket or server socket) drops.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
namespace TCPRelay
{
public class Connection
{
public delegate void delThreadSafeHandleException(System.Exception ex);
public delegate void ConnectionDelegate(Connection conn);
public int DataGridIndex;
Main pMain;
public TcpClient client { get; set; }
public TcpClient server { get; set; }
public String ClientState { get; set; }
public string ListenPort { get; set; }
public string remotePort { get; set; }
public string listenAddress { get; set; }
public string remoteAddress { get; set; }
private TcpListener service { get; set; }
private Main Form
{
get
{
return pMain;
}
}
private NetworkStream clientStream { get; set; }
private NetworkStream serverStream { get; set; }
public Connection(TcpClient client, TcpClient server)
{
clientStream = client.GetStream();
serverStream = server.GetStream();
}
public Connection(String srcAddress, int srcPort, String dstAddress, int dstPort, Main caller)
{
try
{
pMain = caller;
TcpListener _service = new TcpListener((IPAddress.Parse(srcAddress)), srcPort);
//Start the client service and add to connection property
_service.Start();
service = _service;
//Set other useful parameters
listenAddress = srcAddress;
ListenPort = srcPort.ToString();
remoteAddress = dstAddress;
remotePort = dstPort.ToString();
this.ClientState = "Listening";
}
catch (Exception ex)
{
pMain.HandleException(ex);
Thread.CurrentThread.Abort();
}
}
private TcpClient getServerConnection(String address, int port)
{
TcpClient client = new TcpClient(address, port);
if (client.Connected)
{
return client;
}
else
{
throw new Exception(
String.Format("Unable to connect to {0} on port {0}",
address,
port)
);
}
}
private void sendData(Byte[] databuf, NetworkStream stream, int size)
{
bool waiting = true;
while (waiting)
{
if (stream.CanWrite)
{
waiting = false;
stream.Write(databuf, 0, size);
}
else { throw new Exception("Unable to write to network stream"); }
}
}
//Main Looping and data processing goes here
public void ProcessClientRequest()
{
try
{
//Wait for a connection to the client
TcpClient client = service.AcceptTcpClient();
//Get the streams and set the peer endpoints
this.clientStream = client.GetStream();
this.client = client;
//Now that we have a client, lets connect to our server endpoint
TcpClient server = getServerConnection(remoteAddress, int.Parse(remotePort));
//Set some useful parameters
this.server = server;
this.serverStream = server.GetStream();
}
catch (Exception ex)
{
lock (ClientState)
{
this.ClientState = ex.Message;
}
CloseConnection();
Thread.CurrentThread.Abort();
}
while (true)
{
lock (ClientState)
{
checkConnectionStatus(client, server);
}
if (clientStream.CanRead && clientStream.DataAvailable)
{
Byte[] bytes = new Byte[(client.ReceiveBufferSize)];
IAsyncResult result = clientStream.BeginRead(bytes, 0, client.ReceiveBufferSize, null, null);
int size = clientStream.EndRead(result);
sendData(bytes, serverStream, size);
}
if (serverStream.CanRead && serverStream.DataAvailable)
{
Byte[] bytes = new byte[(server.ReceiveBufferSize)];
IAsyncResult result = serverStream.BeginRead(bytes, 0, server.ReceiveBufferSize, null, null);
int size = serverStream.EndRead(result);
sendData(bytes, clientStream, size);
}
}
}
private void checkConnectionStatus(TcpClient _client, TcpClient _server)
{
try
{
if (_client.Client.Poll(0, SelectMode.SelectRead))
{
byte[] buff = new byte[1];
if (_client.Client.Receive(buff, SocketFlags.Peek) == 0)
{
this.ClientState = "Closed";
CloseConnection();
Thread.CurrentThread.Abort();
}
}
else if (_server.Client.Poll(0, SelectMode.SelectRead))
{
byte[] buff = new byte[1];
if (_server.Client.Receive(buff, SocketFlags.Peek) == 0)
{
this.ClientState = "Closed";
CloseConnection();
Thread.CurrentThread.Abort();
}
}
else { this.ClientState = "Connected"; }
}
catch (System.Net.Sockets.SocketException ex)
{
this.ClientState = ex.SocketErrorCode.ToString();
CloseConnection();
Thread.CurrentThread.Abort();
}
}
public void CloseConnection()
{
if (clientStream != null)
{
clientStream.Close();
clientStream.Dispose();
}
if (client != null)
{
client.Close();
}
if (serverStream != null)
{
serverStream.Close();
serverStream.Dispose();
}
if (server != null)
{
server.Close();
}
if (service != null)
{
service.Stop();
}
}
}
}
I also have a "Main" form and a "ConnectionManager" class that i'm playing around with.

The most efficient way of handling this would be to issue a read with a callback, on each stream.
After issuing both reads, sit waiting forever on an object that you use to signal that the thread should stop its work (a ManualResetEvent is the traditional one to use - can be used to signal many threads at once).
When data is received, the OS will call your callback function(s), and you would do your processing in there and then (importantly) queue another read.
This means that your thread is forever idle, waiting on a signal object that tells it that it's time to go away (in a "wake up - time to die" kind of way), and is only ever doing work when the OS tells it that there is data to process.
To be REALLY friendly, you would also do the writes asynchronously, so that one connection cannot starve the other of processing time (in the current implementation, if one write blocks, the other stream never gets serviced).
Finally, to be super good, you would encapsulate this behaviour in an object that takes as a parameter the stream to use, and then simply instantiate two of them, instead of having two streams and doing everything twice in the main code.

After accepting the socket in the middle man I do the following:
private void WaitForData()
{
try
{
if (socketReadCallBack == null)
{
socketReadCallBack = new AsyncCallback(OnDataReceived);
}
ReceiveState rState = new ReceiveState();
rState.Client = mySocket;
mySocket.BeginReceive(rState.Buffer, 0, rState.Buffer.Length, SocketFlags.None,
new AsyncCallback(socketReadCallBack), rState);
}
catch (SocketException excpt)
{
// Process Exception
}
}
Receive State is:
public class ReceiveState
{
public byte[] Buffer = new byte[1024]; //buffer for network i/o
public int DataSize = 0; //data size to be received by the server
public bool DataSizeReceived = false; //whether prefix was received
public MemoryStream Data = new MemoryStream(); //place where data is stored
public Socket Client; //client socket
}
Once data is received my routine "OnDataReceived" processes it. I'm not experiencing any CPU problems with this.
Same code used for both the client and middleman.

Related

Thread sending data to wrong client. Is this a thread safety issue?

I'm currently developing a server that deals with clients using a consumer/producer approach with threads and a blocking collection as shown below:
public class NetworkClient
{
private bool _started = false;
private int _clientId;
private readonly Socket _socket;
private static AutoResetEvent _lastMessageWasAckd = new AutoResetEvent(true);
private static BlockingCollection<byte[]> _messageQueue = new BlockingCollection<byte[]>();
public NetworkClient(Socket socket, int clientId)
{
this._socket = socket;
this._clientId = clientId;
}
public int getClientID() {
return _clientId;
}
public void SendMessage(string message)
{
Console.WriteLine("Adding to player's sending queue " + _clientId);
_messageQueue.Add(Encoding.ASCII.GetBytes(message));
}
public void Start()
{
Thread receiver = new Thread(new ThreadStart(ReceivingThreadProc));
Thread sender = new Thread(new ThreadStart(SendingThreadProc));
receiver.Start();
sender.Start();
this._started = true;
}
public void Stop()
{
this._started = false;
}
private void ReceivingThreadProc()
{
byte[] bytes = new byte[1024];
string data;
try
{
while (_started && _socket.Connected)
{
int numByte = this._socket.Receive(bytes);
data = Encoding.ASCII.GetString(bytes, 0, numByte);
if (numByte == 0)
{
break;
}
if (data == "ACK")
{
_lastMessageWasAckd.Set();
continue;
}
// Acknowledge the message
_socket.Send(Encoding.ASCII.GetBytes("ACK"));
ServerReceiver.onEvent(this._clientId, data);
}
}
catch (Exception e)
{
this._socket.Close();
}
}
private void SendingThreadProc()
{
while (_started && _socket.Connected)
{
_lastMessageWasAckd.WaitOne();
byte[] message = _messageQueue.Take();
Console.WriteLine("Sending the following message to client number: " + _clientId);
Console.WriteLine(System.Text.Encoding.ASCII.GetString(message));
_socket.Send(message);
_lastMessageWasAckd.Reset();
}
}
}
There will be an instance of NetworkClient created for every client that connects for the server. The issue is that sometimes a message is queued to be sent to client 1 (this is confirmed by the Console.Writeline in the SendMessage method) however that message is sent to client 0 (Shown by the console writeline in the SendingThreadProc method) instead. Is this due to a thread safety issue, or am I missing something entirely? This typically happens when two messages are sent right after one another.
Any help would be greatly appreciated.
EDIT:
As many people rightly pointed out I haven't added where I call SendMessage I'll put this class down below:
class NetworkServer
{
private int latestClient = 0;
private ServerReceiver _serverReceiver;
private static readonly Dictionary<int, NetworkClient> clients = new Dictionary<int, NetworkClient>();
public NetworkServer()
{
IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 5656);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this._serverReceiver = new ServerReceiver();
this._serverReceiver.start();
try
{
listener.Bind(endpoint);
listener.Listen(10);
while (true)
{
Socket clientSocket = listener.Accept();
this.OnClientJoin(clientSocket);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static void SendClientMessage(int clientId, string package, CommandType commandType,
Dictionary<string, object> data = null)
{
if (data == null)
{
data = new Dictionary<string, object>();
}
SendClientMessageRaw(clientId, new NetworkCommand(clientId, package, commandType, data).ToJson());
}
public static void SendClientMessageRaw(int id, string message)
{
Console.WriteLine("Supposed to send to client number " + clients[id].getClientID());
clients[id].SendMessage(message);
}
private void OnClientJoin(Socket socket)
{
// Add client to array, perform handshake?
NetworkClient networkClient = new NetworkClient(socket, latestClient);
clients.Add(latestClient, networkClient);
Console.WriteLine("player added :" + latestClient);
networkClient.Start();
latestClient++;
if (latestClient == 2)
{
SendClientMessage(1, "Test", CommandType.Ping, null);
}
}
Could it be because your message queue is static and therefore shared between all NetworkClients? Meaning client A can pick up a message for client B?
Might be as easy as removing static from the properties.

Multi threading with Sockets and passing a string from a class to a form c#

I'm trying to access the string of messageRecieved, which should pass to frmMain.Sort_Data(messageRecived);. However it's null once it hits here. The Console.WriteLine shows the correct data.
public class Client
{
frm_main frmMain = new frm_main();
public string ReturnDat;
//for TCP communications
TcpClient _client = null;
//for sending/receiving data
byte[] data;
public Client(TcpClient client)
{
_client = client;
//start reading data from the client in a separate thread
data = new byte[_client.ReceiveBufferSize];
_client.GetStream().BeginRead(
data, 0, _client.ReceiveBufferSize, receiveMessage, null);
}
public void receiveMessage(IAsyncResult ar)
{
//read from client
int bytesRead;
lock (_client.GetStream())
{
bytesRead = _client.GetStream().EndRead(ar);
}
//if client has disconnected
if (bytesRead < 1)
return;
else
{
//get the message sent
string messageReceived =
ASCIIEncoding.ASCII.GetString(data, 0, bytesRead);
//Console.WriteLine(messageReceived);
frmMain.Sort_Data(messageReceived);
//ReturnDat = messageReceived;
}
//continue reading from client
lock (_client.GetStream())
{
_client.GetStream().BeginRead(
data, 0, _client.ReceiveBufferSize,
receiveMessage, null);
}
}
}
Below is the Sort_Data, which returns nothing when it's hit in the class.
Public void Sort_Data(string data)
{
Messagebox.show(data);
}
Perhaps I'm missing something, or not calling something right?

Sockets - Not sending/receiving data

I'm starting a socket program, and am in the process of setting up a Server and two types of Clients (a requester and an arbiter). I'm in the middle of testing the connections, but they aren't quite working. Right now I just have a button for each form: an "Accept" button for the Arbiter and "Request" for the Requester. Each button should cause a popup on the other form, but neither is working. Also, I've noticed that when I close all programs, the Server is still running in my processes. What am I doing wrong?
Below is the Server code:
namespace FPPLNotificationServer
{
class Server
{
static Socket listenerSocket;
static List<ClientData> _clients;
static void Main(string[] args)
{
Console.WriteLine("Starting server on " + Packet.GetIP4Address());
listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_clients = new List<ClientData>();
IPEndPoint ip = new IPEndPoint(IPAddress.Parse(Packet.GetIP4Address()), 4242);
listenerSocket.Bind(ip);
Thread listenThread = new Thread(ListenThread);
listenThread.Start();
}
static void ListenThread()
{
for (;;)
{
listenerSocket.Listen(0);
_clients.Add(new ClientData(listenerSocket.Accept()));
}
}
public static void Data_IN(object cSocket)
{
Socket clientSocket = (Socket)cSocket;
byte[] Buffer;
int readBytes;
for (;;)
{
try
{
Buffer = new byte[clientSocket.SendBufferSize];
readBytes = clientSocket.Receive(Buffer);
if(readBytes > 0)
{
Packet packet = new Packet(Buffer);
DataManager(packet);
}
}catch(SocketException ex)
{
Console.WriteLine("Client Disconnected");
}
}
}
public static void DataManager(Packet p)
{
switch (p.packetType)
{
case Packet.PacketType.Notification:
foreach(ClientData c in _clients)
{
c.clientSocket.Send(p.ToBytes());
}
break;
}
}
}
class ClientData
{
public Socket clientSocket;
public Thread clientThread;
public string id;
public ClientData()
{
this.id = Guid.NewGuid().ToString();
clientThread = new Thread(Server.Data_IN);
clientThread.Start(clientSocket);
SendRegistrationPacket();
}
public ClientData(Socket clientSocket)
{
this.clientSocket = clientSocket;
this.id = Guid.NewGuid().ToString();
clientThread = new Thread(Server.Data_IN);
clientThread.Start(clientSocket);
SendRegistrationPacket();
}
public void SendRegistrationPacket()
{
Packet p = new Packet(Packet.PacketType.Registration, "server");
p.Gdata.Add(id);
clientSocket.Send(p.ToBytes());
}
}
}
ServerData
namespace FPPLNotificationServerData
{
[Serializable]
public class Packet
{
public List<String> Gdata;
public int packetInt;
public bool packetBool;
public string senderID;
public PacketType packetType;
public string PlantName, ProductSegment, ProductCustomer;
public int PlantNumber;
public string ProductNumber, ProductAltNumber;
public string ProductDiscription;
public int ProductLine;
public string ProductClass, ProductLocation;
public int ProductMcDFactor;
public Packet(PacketType type, String senderID)
{
Gdata = new List<string>();
this.senderID = senderID;
this.packetType = type;
}
public Packet(byte[] packetBytes)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream(packetBytes);
Packet p = (Packet)bf.Deserialize(ms);
ms.Close();
this.Gdata = p.Gdata;
this.senderID = p.senderID;
this.packetType = p.packetType;
this.packetBool = p.packetBool;
this.packetInt = p.packetInt;
}
public byte[] ToBytes()
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, this);
byte[] bytes = ms.ToArray();
ms.Close();
return bytes;
}
public static string GetIP4Address()
{
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
foreach(IPAddress i in ips)
{
if(i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
return i.ToString();
}
}
return "127.0.0.1";
}
public enum PacketType
{
Registration,
Chat,
Notification,
Request,
ArbiterDecision,
Accept,
Decline
}
}
}
Request Class:
namespace FPPLRequestClient
{
public partial class frm_Request : Form
{
public static Socket master;
public static string name;
public static string id;
public bool isConnected;
public frm_Request()
{
InitializeComponent();
string IP = "127.0.0.1";
master = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipEP = new IPEndPoint(IPAddress.Parse(IP), 4242);
try
{
master.Connect(ipEP);
isConnected = true;
}
catch (Exception)
{
isConnected = false;
}
string connectionStatus = isConnected ? "Connected" : "Disconnected";
this.lbl_Status.Text = "Status: " + connectionStatus;
Thread t = new Thread(Data_IN);
t.Start();
}
void Data_IN()
{
byte[] Buffer;
int readBytes;
while (isConnected)
{
try
{
Buffer = new byte[master.SendBufferSize];
readBytes = master.Receive(Buffer);
if(readBytes > 0)
{
DataManager(new Packet(Buffer));
}
}catch(SocketException ex)
{
isConnected = false;
this.Dispose();
}
}
}//END DATA IN
void DataManager(Packet p)
{
switch (p.packetType)
{
case Packet.PacketType.Registration:
id = p.Gdata[0];
break;
case Packet.PacketType.Accept:
//MessageBox.Show(p.ProductNumber);
this.lbl_Status.Text = p.ProductNumber + " accepted";
Invalidate();
break;
}
}
private void btn_Request_Click(object sender, EventArgs e)
{
Packet p = new Packet(Packet.PacketType.Request, id);
p.ProductNumber = "123456";
master.Send(p.ToBytes());
}
}
}
Arbiter Class:
namespace FPPLArbiterClient
{
public partial class frm_Arbiter : Form
{
public static Socket master;
public static string name;
public static string id;
public bool isConnected;
public frm_Arbiter()
{
InitializeComponent();
string IP = "127.0.0.1";
master = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipEP = new IPEndPoint(IPAddress.Parse(IP), 4242);
try
{
master.Connect(ipEP);
isConnected = true;
}
catch (Exception)
{
isConnected = false;
}
string connectionStatus = isConnected ? "Connected" : "Disconnected";
this.lbl_Status.Text = "Status: " + connectionStatus;
Thread t = new Thread(Data_IN);
t.Start();
}
void Data_IN()
{
byte[] Buffer;
int readBytes;
while (isConnected)
{
try
{
Buffer = new byte[master.SendBufferSize];
readBytes = master.Receive(Buffer);
if(readBytes > 0)
{
DataManager(new Packet(Buffer));
}
}catch(SocketException ex)
{
isConnected = false;
this.Dispose();
}
}
}//END DATA IN
void DataManager(Packet p)
{
switch (p.packetType)
{
case Packet.PacketType.Registration:
id = p.Gdata[0];
break;
case Packet.PacketType.Request:
MessageBox.Show(p.ProductNumber + " Requested from " + p.senderID);
break;
}
}
private void btn_Accept_Click(object sender, EventArgs e)
{
MessageBox.Show("Sending acceptance of 126456");
Packet p = new Packet(Packet.PacketType.Accept, id);
p.ProductNumber = "123456";
master.Send(p.ToBytes());
}
}
}
This is my first dive into socket programming.
To start with your last question first, Receive will block until data becomes available unless you specify a timeout. Since your threads are foreground threads, this will prevent your application from terminating. See https://msdn.microsoft.com/en-us/library/8s4y8aff(v=vs.110).aspx. Either use a timeout, and/or make your threads background threads causing them to terminate when you close your application's main thread. Set the created thread's IsBackground property to true to achieve this. (Also, in the article above notice the paragraph about Shutdown and the Receive method returning an empty array. This is your hint to gracefully close the connection on your side).
The TCP/IP stack will send data at its own discretion (Nagle's algorithm), meaning you'll occasionally receive a buffer containing several or partial messages. Since you have "silent" error handling in your thread, perhaps your thread terminates prematurely because of a corrupted message? Place everything you receive in a buffer and check the buffer for complete messages in a separate step/thread before passing them on to your message handler.
No clear answers here I'm afraid, but if the check for corrupted messages doesn't help, look at the Socket samples on MSDN. It's probably just a tiny detail you're missing.
you are making a fundamental and common TCP error. TCP is a byte oriented streaming protocol, not message oriented. Your receive code assumes that it receives one Packet when it reads. This is not guaranteed, you might receive 1 byte, 20 bytes, or whatever. You must loop in the receive till you get all of one message. This means you have to know when you have read it all. Either there needs to be a header or some sentinel at the end.

Transmitting/Sending big packet safely using TcpClient/Socket

I am writing a TCP based client that need to send and receive data. I have used the Asynchronous Programming Model (APM) provided for Socket class by the .NET Framework.
After being connected to the socket, I start wait for data on the socket using BeginReceive.
Now, while I am waiting for the data on the Socket, I may need to send data over the socket. And the send method can be called multiple times,
So i have make sure that
All the bytes from previous Send call is entirely sent.
The way i am sending the Data is safe considering that, while a data send is in progress, any call to send data can be made.
This is my first work on socket, So is my approach right to send data ?
private readonly object writeLock = new object();
public void Send(NetworkCommand cmd)
{
var data = cmd.ToBytesWithLengthPrefix();
ThreadPool.QueueUserWorkItem(AsyncDataSent, data);
}
private int bytesSent;
private void AsyncDataSent(object odata)
{
lock (writeLock)
{
var data = (byte[])odata;
int total = data.Length;
bytesSent = 0;
int buf = Globals.BUFFER_SIZE;
while (bytesSent < total)
{
if (total - bytesSent < Globals.BUFFER_SIZE)
{
buf = total - bytesSent;
}
IAsyncResult ar = socket.BeginSend(data, bytesSent, buf, SocketFlags.None, DataSentCallback, data);
ar.AsyncWaitHandle.WaitOne();
}
}
}
How object is changed into byte[], sometimes the NetworkCommand can be as big as 0.5 MB
public byte[] ToBytesWithLengthPrefix()
{
var stream = new MemoryStream();
try
{
Serializer.SerializeWithLengthPrefix(stream, this, PrefixStyle.Fixed32);
return stream.ToArray();
}
finally
{
stream.Close();
stream.Dispose();
}
}
Complete class
namespace Cybotech.Network
{
public delegate void ConnectedDelegate(IPEndPoint ep);
public delegate void DisconnectedDelegate(IPEndPoint ep);
public delegate void CommandReceivedDelagate(IPEndPoint ep, NetworkCommand cmd);
}
using System;
using System.Net;
using System.Net.Sockets;
using Cybotech.Helper;
using Cybotech.IO;
namespace Cybotech.Network
{
public class ClientState : IDisposable
{
private int _id;
private int _port;
private IPAddress _ip;
private IPEndPoint _endPoint;
private Socket _socket;
private ForwardStream _stream;
private byte[] _buffer;
public ClientState(IPEndPoint endPoint, Socket socket)
{
Init(endPoint, socket);
}
private void Init(IPEndPoint endPoint, Socket socket)
{
_endPoint = endPoint;
_ip = _endPoint.Address;
_port = _endPoint.Port;
_id = endPoint.GetHashCode();
_socket = socket;
_stream = new ForwardStream();
_buffer = new byte[Globals.BUFFER_SIZE];
}
public int Id
{
get { return _id; }
}
public int Port
{
get { return _port; }
}
public IPAddress Ip
{
get { return _ip; }
}
public IPEndPoint EndPoint
{
get { return _endPoint; }
}
public Socket Socket
{
get { return _socket; }
}
public ForwardStream Stream
{
get { return _stream; }
}
public byte[] Buffer
{
get { return _buffer; }
set { _buffer = value; }
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_stream != null)
{
_stream.Close();
_stream.Dispose();
}
if (_socket != null)
{
_socket.Close();
}
}
}
public void Dispose()
{
Dispose(true);
}
}
}
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using Cybotech.Command;
using Cybotech.Network;
namespace ExamServer.Network
{
public class TcpServer : IDisposable
{
private Socket socket;
private bool secure;
private readonly Dictionary<IPEndPoint, ClientState> clients = new Dictionary<IPEndPoint, ClientState>();
//public events
#region Events
public event CommandDelegate CommandReceived;
public event ConnectedDelegate ClientAdded;
public event DisconnectedDelegate ClientRemoved;
#endregion
//event invokers
#region Event Invoke methods
protected virtual void OnCommandReceived(IPEndPoint ep, NetworkCommand command)
{
CommandDelegate handler = CommandReceived;
if (handler != null) handler(ep, command);
}
protected virtual void OnClientAdded(IPEndPoint ep)
{
ConnectedDelegate handler = ClientAdded;
if (handler != null) handler(ep);
}
protected virtual void OnClientDisconnect(IPEndPoint ep)
{
DisconnectedDelegate handler = ClientRemoved;
if (handler != null) handler(ep);
}
#endregion
//public property
public string CertificatePath { get; set; }
public TcpServer(EndPoint endPoint, bool secure)
{
StartServer(endPoint, secure);
}
public TcpServer(IPAddress ip, int port, bool secure)
{
StartServer(new IPEndPoint(ip, port), secure);
}
public TcpServer(string host, int port, bool secure)
{
StartServer(new IPEndPoint(IPAddress.Parse(host), port), secure);
}
private void StartServer(EndPoint ep, bool ssl)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ep);
socket.Listen(150);
this.secure = ssl;
socket.BeginAccept(AcceptClientCallback, null);
}
private void AcceptClientCallback(IAsyncResult ar)
{
Socket client = socket.EndAccept(ar);
var ep = (IPEndPoint) client.RemoteEndPoint;
var state = new ClientState(ep, client);
if (secure)
{
//TODO : handle client for ssl authentication
}
//add client to
clients.Add(ep, state);
OnClientAdded(ep);
client.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, ReceiveDataCallback, state);
//var thread = new Thread(ReceiveDataCallback);
//thread.Start(state);
}
private void ReceiveDataCallback(IAsyncResult ar)
{
ClientState state = (ClientState)ar.AsyncState;
try
{
var bytesRead = state.Socket.EndReceive(ar);
state.Stream.Write(state.Buffer, 0, bytesRead);
// check available commands
while (state.Stream.LengthPrefix > 0)
{
NetworkCommand cmd = NetworkCommand.CreateFromStream(state.Stream);
OnCommandReceived(state.EndPoint, cmd);
}
//start reading data again
state.Socket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, ReceiveDataCallback, state);
}
catch (SocketException ex)
{
if (ex.NativeErrorCode.Equals(10054))
{
RemoveClient(state.EndPoint);
}
}
}
private void RemoveClient(IPEndPoint ep)
{
OnClientDisconnect(ep);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
//TODO : dispose all the client related socket stuff
}
}
public void Dispose()
{
Dispose(true);
}
}
}
The same client won't be able to send data to you unless he finishes sending the current bytes.
So on the server side, you will receive the completed data no interrupted by other new messages from that client, but take in consideration that not all the message sent will be received by one hit if it is too big, but still, it is one message in the end after receiving is finished.
As you are using TCP, the network protocol will ensure that packets are received in the same order as sent.
Regarding thread safety it depends a bit on the actual class which you are using for sending. The declaration part is missing in your provided code fragment.
Given by the name you seem to use Socket and this is thread-safe, so every send is actually atomic, if you use any flavor of Stream, then it is not thread-safe and you need some form of synchronization like a lock, which you are currently using anyway.
If you are sending large packets, then it is important to split the receiving and processing part into two different threads. The TCP buffer is actually a lot smaller than one would think and unfortunately it is not covered inside the logs when it is full as the protocol will keep performing resend until everything has been received.

Send a Message Box to a client in my Domain from C# Windows Form

I have got a windows forms project than copying files and folders to clients in my domain. When copying file or copying directory process to [x]clients in my domain. I want to send it a Messagebox that says "There is a new folder or file in your [xdirectory]".
I can't do it by Messenger service because of Messenger service is does not working in XP Sp2 so I need another way for this. Maybe a client/server side application could be make. There will be a listener app in client then I will send it a messagebox.show code then it will show us a messagebox. etc.
I did something similar once before. I got most of this code from somewhere else, but I cannot remember from where.
First the Server Code:
public class HSTcpServer
{
private TcpListener m_listener;
private IPAddress m_address = IPAddress.Any;
private int m_port;
private bool m_listening;
private object m_syncRoot = new object();
public event EventHandler<TcpMessageReceivedEventArgs> MessageReceived;
public HSTcpServer(int port)
{
m_port = port;
}
public IPAddress Address
{
get { return m_address; }
}
public int Port
{
get { return m_port; }
}
public bool Listening
{
get { return m_listening; }
}
public void Listen()
{
try
{
lock (m_syncRoot)
{
m_listener = new TcpListener(m_address, m_port);
// fire up the server
m_listener.Start();
// set listening bit
m_listening = true;
}
// Enter the listening loop.
do
{
Trace.Write("Looking for someone to talk to... ");
// Wait for connection
TcpClient newClient = m_listener.AcceptTcpClient();
//Trace.WriteLine("Connected to new client");
// queue a request to take care of the client
ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessClient), newClient);
}
while (m_listening);
}
catch (SocketException se)
{
Trace.WriteLine("SocketException: " + se.ToString());
}
finally
{
// shut it down
StopListening();
}
}
public void StopListening()
{
if (m_listening)
{
lock (m_syncRoot)
{
// set listening bit
m_listening = false;
// shut it down
m_listener.Stop();
}
}
}
private void sendMessage(string message)
{
// Copy to a temporary variable to be thread-safe.
EventHandler<TcpMessageReceivedEventArgs> messageReceived = MessageReceived;
if (messageReceived != null)
messageReceived(this, new TcpMessageReceivedEventArgs(message));
}
private void ProcessClient(object client)
{
TcpClient newClient = (TcpClient)client;
try
{
// Buffer for reading data
byte[] bytes = new byte[1024];
StringBuilder clientData = new StringBuilder();
// get the stream to talk to the client over
using (NetworkStream ns = newClient.GetStream())
{
// set initial read timeout to 1 minute to allow for connection
ns.ReadTimeout = 60000;
// Loop to receive all the data sent by the client.
int bytesRead = 0;
do
{
// read the data
try
{
bytesRead = ns.Read(bytes, 0, bytes.Length);
if (bytesRead > 0)
{
// Translate data bytes to an ASCII string and append
clientData.Append(Encoding.ASCII.GetString(bytes, 0, bytesRead));
// decrease read timeout to 1 second now that data is
// coming in
ns.ReadTimeout = 1000;
}
}
catch (IOException ioe)
{
// read timed out, all data has been retrieved
Trace.WriteLine("Read timed out: {0}", ioe.ToString());
bytesRead = 0;
}
}
while (bytesRead > 0);
bytes = Encoding.ASCII.GetBytes("clowns");
// Send back a response.
ns.Write(bytes, 0, bytes.Length);
sendMessage(clientData.ToString());
}
}
finally
{
// stop talking to client
if (newClient != null)
newClient.Close();
}
}
}
public class TcpMessageReceivedEventArgs : EventArgs
{
private string m_message;
public TcpMessageReceivedEventArgs(string message)
{
m_message = message;
}
public string Message
{
get
{
return m_message;
}
}
}
The Client Code:
class HSTcpClient
{
private TcpClient _client;
private IPAddress _address;
private int _port;
private IPEndPoint _endPoint;
private bool _disposed;
public HSTcpClient(IPAddress address, int port)
{
_address = address;
_port = port;
_endPoint = new IPEndPoint(_address, _port);
}
public void SendForwardedClientMessage(int senderId, int receiverId, int hsId)
{
SendMessage(senderId.ToString() + ":" + receiverId.ToString() + ":" + hsId.ToString());
}
public void SendUpdatedCGBMessage()
{
SendMessage("Update your CGB you clowns");
}
public void SendMessage(string msg)
{
try
{
_client = new TcpClient();
_client.Connect(_endPoint);
// Get the bytes to send for the message
byte[] bytes = Encoding.ASCII.GetBytes(msg);
// Get the stream to talk to the server on
using (NetworkStream ns = _client.GetStream())
{
// Send message
Trace.WriteLine("Sending message to server: " + msg);
ns.Write(bytes, 0, bytes.Length);
// Get the response
// Buffer to store the response bytes
bytes = new byte[1024];
// Display the response
int bytesRead = ns.Read(bytes, 0, bytes.Length);
string serverResponse = Encoding.ASCII.GetString(bytes, 0, bytesRead);
Trace.WriteLine("Server said: " + serverResponse);
}
}
catch (SocketException se)
{
Trace.WriteLine("There was an error talking to the server: " +
se.ToString());
}
finally
{
Dispose();
}
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
System.GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (_client != null)
_client.Close();
}
_disposed = true;
}
}
#endregion
}
Then to use, create a server variable in your form code:
private HSTcpServer m_server;
and I created a background worker thread:
private System.ComponentModel.BackgroundWorker hsTcpServerThread;
handled the DoWork event:
private void hsTcpServerThread_DoWork(object sender, DoWorkEventArgs e)
{
m_server = new HSTcpServer(<pick your port>);
m_server.MessageReceived += new EventHandler<TcpMessageReceivedEventArgs>(m_server_MessageReceived);
m_server.Listen();
}
Then handle the message recieved event:
void m_server_MessageReceived(object sender, TcpMessageReceivedEventArgs e)
{
//<your code here> - e contains message details
}
Then to send a message to the server:
HSTcpClient client = new HSTcpClient(<ip address>, <port you picked>);
client.SendForwardedClientMessage(<message details>);
Hopefully I got everything in there.
You can use the FileSystemWatcher in the client. That way you do not have to deal with remoting or listening on ports.
If you really want to communicate between the two machines you can do using remoting, or via the TcpListener.

Categories

Resources