I am trying to make an advanced chat in C#. I am not new to programming but it is close to my first TCP chat.
The problem is that my Socket (server) looks to not receive any datas. In my void ReceiveDataListener which is a BackgroundWorker, I added some Console.WriteLine(); to check where it locks and it only display the first Console.WriteLine("Receive Data Listener 0"). I know it is normal that Socket.Receive() lock until some datas are received but it seems to stay locked even if I send datas.
I also want to add that my event onClientConnect and onClientDisconnect are invoked fine so I know the clients connects fine.
Here is the code of my Server class :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.ComponentModel;
using System.Threading;
namespace JAChat.Library
{
class SocketServer
{
private Socket socket;
private BackgroundWorker bwSocketConnectListener;
private BackgroundWorker bwCheckIfConnected;
private BackgroundWorker bwReceiveDataListener;
private List<ClientManager> clientsList;
#region Constructor
public SocketServer(int port)
{
clientsList = new List<ClientManager>();
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(new IPEndPoint(IPAddress.Any, port));
socket.Listen(100);
bwSocketConnectListener = new BackgroundWorker();
bwSocketConnectListener.DoWork += new DoWorkEventHandler(ListenSocketConnection);
bwSocketConnectListener.RunWorkerAsync();
bwCheckIfConnected = new BackgroundWorker();
bwCheckIfConnected.DoWork += CheckIfClientStillConnectedThread;
bwCheckIfConnected.RunWorkerAsync();
bwReceiveDataListener = new BackgroundWorker();
bwReceiveDataListener.DoWork += ReceiveDataListener;
bwReceiveDataListener.RunWorkerAsync();
}
#endregion
#region Getter
public List<ClientManager> connectedClients
{
get
{
return clientsList;
}
}
#endregion
#region Public Methods
/// <summary>
/// Parse and send the command object to targets
/// </summary>
public void sendCommand(Command cmd)
{
BackgroundWorker test = new BackgroundWorker();
test.DoWork += delegate {
foreach(ClientManager cManager in clientsList){
cManager.sendCommand(cmd);
}
};
test.RunWorkerAsync();
}
/// <summary>
/// Disconnect and close the socket
/// </summary>
public void Disconnect()
{
socket.Disconnect(false);
socket.Close();
socket = null; //Stop some background worker
}
#endregion
#region Private Methods
private void ListenSocketConnection(object sender, DoWorkEventArgs e)
{
while (socket != null)
{
//Get and WAIT for new connection
ClientManager newClientManager = new ClientManager(socket.Accept());
clientsList.Add(newClientManager);
onClientConnect.Invoke(newClientManager);
}
}
private void CheckIfClientStillConnectedThread(object sender, DoWorkEventArgs e){
while(socket != null){
for(int i=0;i<clientsList.Count;i++){
if(clientsList[i].socket.Poll(10,SelectMode.SelectRead) && clientsList[i].socket.Available==0){
clientsList[i].socket.Close();
onClientDisconnect.Invoke(clientsList[i]);
clientsList.Remove(clientsList[i]);
i--;
}
}
Thread.Sleep(5);
}
}
private void ReceiveDataListener(object sender, DoWorkEventArgs e){
while (socket != null){
Console.WriteLine("Receive Data Listener 0");
//Read the command's Type.
byte[] buffer = new byte[4];
int readBytes = this.socket.Receive(buffer, 0, 4, SocketFlags.None);
Console.WriteLine("Receive Data Listener 1");
if (readBytes == 0)
break;
Console.WriteLine("Receive Data Listener 2");
CommandType cmdType = (CommandType)(BitConverter.ToInt32(buffer, 0));
Console.WriteLine("Receive Data Listener 3");
//Read the sender IP size.
buffer = new byte[4];
readBytes = this.socket.Receive(buffer, 0, 4, SocketFlags.None);
if (readBytes == 0)
break;
int senderIPSize = BitConverter.ToInt32(buffer, 0);
//Read the sender IP.
buffer = new byte[senderIPSize];
readBytes = this.socket.Receive(buffer, 0, senderIPSize, SocketFlags.None);
if (readBytes == 0)
break;
IPAddress cmdSenderIP = IPAddress.Parse(System.Text.Encoding.ASCII.GetString(buffer));
//Read the sender name size.
buffer = new byte[4];
readBytes = this.socket.Receive(buffer, 0, 4, SocketFlags.None);
if (readBytes == 0)
break;
int senderNameSize = BitConverter.ToInt32(buffer, 0);
//Read the sender name.
buffer = new byte[senderNameSize];
readBytes = this.socket.Receive(buffer, 0, senderNameSize, SocketFlags.None);
if (readBytes == 0)
break;
string cmdSenderName = System.Text.Encoding.Unicode.GetString(buffer);
//Read target IP size.
string cmdTarget = "";
buffer = new byte[4];
readBytes = this.socket.Receive(buffer, 0, 4, SocketFlags.None);
if (readBytes == 0)
break;
int targetIPSize = BitConverter.ToInt32(buffer, 0);
//Read the command's target.
buffer = new byte[targetIPSize];
readBytes = this.socket.Receive(buffer, 0, targetIPSize, SocketFlags.None);
if (readBytes == 0)
break;
cmdTarget = System.Text.Encoding.ASCII.GetString(buffer);
//Read the command's MetaData size.
string cmdMetaData = "";
buffer = new byte[4];
readBytes = this.socket.Receive(buffer, 0, 4, SocketFlags.None);
if (readBytes == 0)
break;
int metaDataSize = BitConverter.ToInt32(buffer, 0);
//Read the command's Meta data.
buffer = new byte[metaDataSize];
readBytes = this.socket.Receive(buffer, 0, metaDataSize, SocketFlags.None);
if (readBytes == 0)
break;
cmdMetaData = System.Text.Encoding.Unicode.GetString(buffer);
//Create the command object
Command cmd = new Command(cmdType, cmdSenderIP, cmdSenderName, IPAddress.Parse(cmdTarget), cmdMetaData);
this.onCommandReceived(cmd);
}
Console.WriteLine("Receive data listener closed");
}
#endregion
#region Events
public delegate void OnClientConnectEventHandler(ClientManager client);
/// <summary>
/// Events invoked when a client connect to the server
/// </summary>
public event OnClientConnectEventHandler onClientConnect = delegate { };
public delegate void OnClientDisconnectEventHandler(ClientManager client);
/// <summary>
/// Events invoked when a client disconnect from the server
/// </summary>
public event OnClientDisconnectEventHandler onClientDisconnect = delegate { };
public delegate void OnCommandReceivedEventHandler(Command cmd);
/// <summary>
/// Events invoked when a command has been sent to the server
/// </summary>
public event OnCommandReceivedEventHandler onCommandReceived = delegate { };
#endregion
}
}
and here is the code that I use to test the server by sending datas :
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect("localhost", 2000);
networkStream = new NetworkStream(clientSocket);
//CommandType
byte[] buffer = new byte[4];
buffer = BitConverter.GetBytes(1);
this.networkStream.Write(buffer, 0, 4);
this.networkStream.Flush();
//Sender IP + Size
byte[] senderIPBuffer = Encoding.ASCII.GetBytes("192.54.67.8");
buffer = new byte[4];
buffer = BitConverter.GetBytes(senderIPBuffer.Length);
this.networkStream.Write(buffer, 0, 4);
this.networkStream.Flush();
this.networkStream.Write(senderIPBuffer, 0, senderIPBuffer.Length);
this.networkStream.Flush();
//Sender Name + Size
byte[] senderNameBuffer = Encoding.ASCII.GetBytes("James");
buffer = new byte[4];
buffer = BitConverter.GetBytes(senderNameBuffer.Length);
this.networkStream.Write(buffer, 0, 4);
this.networkStream.Flush();
this.networkStream.Write(senderNameBuffer, 0, senderNameBuffer.Length);
this.networkStream.Flush();
//Command Target IP + Size
byte[] targetIPBuffer = Encoding.ASCII.GetBytes("192.43.54.6");
buffer = new byte[4];
buffer = BitConverter.GetBytes(targetIPBuffer.Length);
this.networkStream.Write(buffer, 0, 4);
this.networkStream.Flush();
this.networkStream.Write(targetIPBuffer, 0, targetIPBuffer.Length);
this.networkStream.Flush();
//Command MetaData + Size
byte[] metaBuffer = Encoding.Unicode.GetBytes("Metadata contents");
buffer = new byte[4];
buffer = BitConverter.GetBytes(metaBuffer.Length);
this.networkStream.Write(buffer, 0, 4);
this.networkStream.Flush();
this.networkStream.Write(metaBuffer, 0, metaBuffer.Length);
this.networkStream.Flush();
SocketServer has a class-level variable named "socket"
SocketServer's constructor creates a socket for listening on the specified port and saves this as the value of socket
ListenSocketConnection is calling Socket.Accept (good) and keeping a list of connections
ERROR: ReceiveDataListener is trying to read from the socket that is listening on the specified port instead of reading from the individual sockets that were returned by the Accept call in ListenSocketConnection
Note: the server throws an exception right on startup (for me at least) in ReceiveDataListener, before any client has even attempted to connect, since the socket reader worker immediately tries to read from a socket that is in the listen state.
Hope that helps - Harold
Related
I have a Java android code that sends data (image or text) to a C# application, to receive these data I'm using Async socket. But exists a problem that is relative to BeginReceive() function is not receiving the complete data when is sent an image.. Then how I can make a kind of "loop" to receive full data and after show the image on Picturebox (for example)?
Form
private Listener listener;
private Thread startListen;
private Bitmap _buffer;
public frmMain()
{
InitializeComponent();
}
private void serverReceivedImage(Client client, byte[] image)
{
try
{
byte[] newImage = new byte[image.Length - 6];
Array.Copy(image, 6, newImage, 0, newImage.Length);
using (var stream = new MemoryStream(newImage))
{
using (var msInner = new MemoryStream())
{
stream.Seek(2, SeekOrigin.Begin);
using (DeflateStream z = new DeflateStream(stream, CompressionMode.Decompress))
{
z.CopyTo(msInner);
}
msInner.Seek(0, SeekOrigin.Begin);
var bitmap = new Bitmap(msInner);
Invoke(new frmMain.ImageCompleteDelegate(ImageComplete), new object[] { bitmap });
}
}
}
catch (Exception)
{
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
}
private delegate void ImageCompleteDelegate(Bitmap bitmap);
private void ImageComplete(Bitmap bitmap)
{
if (_buffer != null)
_buffer.Dispose();
_buffer = new Bitmap(bitmap);
pictureBox1.Size = _buffer.Size;
pictureBox1.Invalidate();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
if (_buffer == null) return;
e.Graphics.DrawImage(_buffer, 0, 0);
}
private void startToolStripMenuItem_Click(object sender, EventArgs e)
{
startListen = new Thread(listen);
startListen.Start();
}
private void listen()
{
listener = new Listener();
listener.BeginListen(101);
listener.receivedImage += new Listener.ReceivedImageEventHandler(serverReceivedImage);
startToolStripMenuItem.Enabled = false;
}
Listener
class Listener
{
private Socket s;
public List<Client> clients;
public delegate void ReceivedImageEventHandler(Client client, byte[] image);
public event ReceivedImageEventHandler receivedImage;
private bool listening = false;
public Listener()
{
clients = new List<Client>();
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public bool Running
{
get { return listening; }
}
public void BeginListen(int port)
{
s.Bind(new IPEndPoint(IPAddress.Any, port));
s.Listen(100);
s.BeginAccept(new AsyncCallback(AcceptCallback), s);
listening = true;
}
public void StopListen()
{
if (listening == true)
{
s.Close();
listening = false;
}
}
void AcceptCallback(IAsyncResult ar)
{
Socket handler = (Socket)ar.AsyncState;
Socket sock = handler.EndAccept(ar);
Client client = new Client(sock);
clients.Add(client);
sock.BeginReceive(client.buffer, 0, client.buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), client);
client.Send("REQUEST_PRINT" + Environment.NewLine);
handler.BeginAccept(new AsyncCallback(AcceptCallback), handler);
}
void ReadCallback(IAsyncResult ar)
{
Client client = (Client)ar.AsyncState;
try
{
int rec = client.sock.EndReceive(ar);
if (rec != 0)
{
string data = Encoding.UTF8.GetString(client.buffer, 0, rec);
if (data.Contains("SCREEN"))
{
byte[] bytes = Encoding.UTF8.GetBytes(data);
receivedImage(client, bytes);
}
else // not is a image, is a text
{
// prepare text to show in TextBox
}
}
else
{
Disconnected(client);
return;
}
client.sock.BeginReceive(client.buffer, 0, client.buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), client);
}
catch
{
Disconnected(client);
client.sock.Close();
clients.Remove(client);
}
}
}
Client
class Client
{
public Socket sock;
public byte[] buffer = new byte[8192];
public Client(Socket sock)
{
this.sock = sock;
}
public void Send(string data)
{
byte[] buffer = Encoding.ASCII.GetBytes(data);
sock.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback((ar) =>
{
sock.EndSend(ar);
}), buffer);
}
}
Android code
private byte[] compress(byte[] data) {
Deflater deflater = new Deflater();
deflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
deflater.finish();
byte[] buffer = new byte[1024];
while (!deflater.finished()) {
int count = deflater.deflate(buffer);
outputStream.write(buffer, 0, count);
}
outputStream.close();
byte[] output = outputStream.toByteArray();
return output;
}
public static DataOutputStream dos;
public static byte[] array;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
array = compress(bos.toByteArray());
//...
dos = new DataOutputStream(SocketBackgroundService.clientSocket.getOutputStream());
byte[] header = ("SCREEN").getBytes(StandardCharsets.UTF_8);
byte[] dataToSend = new byte[header.length + array.length];
System.arraycopy(header, 0, dataToSend, 0, header.length);
System.arraycopy(array, 0, dataToSend, header.length, array.length);
dos.writeInt(dataToSend.length);
dos.write(dataToSend, 0, dataToSend.length);
dos.flush();
EDITION
i'm always getting the error Invalid Parameter in this line
var bitmap = new Bitmap(msInner);
and using compression also happens the same here
z.CopyTo(msInner);
IvalidDataException
on ServerReceivedImage() method respectively.
using this
File.WriteAllBytes(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "image.png"), newImage);
i noted that is receiving only 15KB (size of file without use compression).
I was writing a comment but it does not give me enough space to express my frustration with your code.
My main points are
You try to recompress and perfectly compressed image. PNG is portable network graphics. It was designed for network transfers. If it is acceptable you should use something like jpeg.
You just decode received buffer using UTF8.GetString and search for a text, then re-encode that string and try to decompress and read an image from it, by starting from index 6 which is pretty meaningless considering you added a two byte size field to the start of stream and you really do not know position of "SCREEN".
You do not check if you have received ALL of the stream data.
All of the code looks like you have scoured the SO questions and answers and created a copy pasta.
Now my recommendations.
When transferring data from network, do not try to invent wheels. Try something like gRPC which has both android java and c# packages.
If you will use raw data, please, please know your bytes.
I assume you will extend your code by adding new command pairs. Since you have no magic markers of some kind of signal system, it will be very hard for you to distinguish data from header. For a simple implementation add some kind of magic data to your header and search for that data, then read header and then read data. You may need to read from socket again and again until you receive all of the data.
424A72 0600 53435245454E 008E0005 ..... 724A42
B J r 6 S C R E E N 36352 ..... rJB
this sample data shows that we have a valid stream by looking at "BJr". Then read a 2 byte unsigned integer to read command size which is 6 for SCREEN. Read command and then read four bytes unsigned length for command data. For our sample it is 36352. Just to be safe I've added an end of command marker "rJB".
For a bonus point try reducing memory allocations / copies, you can look at System.Span<T>
So I'm trying to make a chatroom. I use TCP Sockets to send all information. But when I send a byte array the receiving socket's buffer has the last byte missing. it's 0 cause the byte array is 255 big, so the left over bytes are 0. I've checked through debug mode, at the point when the packet was sent, the array is correct. But at the break point when the sockets finished receiving it's missing that last byte. Any reason why this would be happening? I saw another thread which said you had to stop the thread till the sockets finished receiving, but I'm using AsyncCallBack which to my knowledge is called when the socket has finished receiving.
Also the first byte in each packet is supposed to be the string size (To account for the extra empty bytes).
PacketClass:
public class Packet
{
public byte[] Buffer;
public Packet(string message)
{
Buffer = new byte[255];
byte[] messageArray = Encoding.ASCII.GetBytes(message);
Buffer[0] = (byte)messageArray.GetLength(0);
for (int i = 0; i < messageArray.GetLength(0); i++)
{
Buffer[i+1] = messageArray[i];
}
}
public Packet(byte[] buffer)
{
Buffer = buffer;
}
public string GetMessage()
{
List<byte> messageBuffer = new List<byte>();
for (int i = 1; i <= Buffer[0]; i++)
{
messageBuffer.Add(Buffer[i]);
}
return Encoding.ASCII.GetString(messageBuffer.ToArray());
}
}
SocketClass:
class Client
{
public static List<Client> connectedClients = new List<Client>();
public Socket Sock;
public byte[] Buffer = new byte[255];
public Client(Socket pSock)
{
Sock = pSock;
Sock.BeginReceive(Buffer, 0, 255, SocketFlags.None, new AsyncCallback(RecieveCallBack), null);
}
public void Send(byte[] pBuffer)
{
Sock.BeginSend(pBuffer, 0, pBuffer.GetLength(0), SocketFlags.None, new AsyncCallback(SendCallBack), null);
}
public void SendCallBack(IAsyncResult AR)
{
Console.WriteLine("Sent");
Sock.EndSend(AR);
}
public void RecieveCallBack(IAsyncResult AR)
{
Sock.EndReceive(AR);
Packet recPacket = new Packet(Buffer);
Console.WriteLine(recPacket.GetMessage());
Sock.BeginReceive(Buffer, 0, 255, SocketFlags.None, new AsyncCallback(RecieveCallBack), null);
}
}
Main Server Program
`class Client
{
public static List connectedClients = new List();
public Socket Sock;
public byte[] Buffer = new byte[255];
public Client(Socket pSock)
{
Sock = pSock;
Sock.BeginReceive(Buffer, 0, 255, SocketFlags.None, new AsyncCallback(RecieveCallBack), null);
}
public void Send(byte[] pBuffer)
{
Sock.BeginSend(pBuffer, 0, pBuffer.Length, SocketFlags.None, new AsyncCallback(SendCallBack), null);
}
public void SendCallBack(IAsyncResult AR)
{
Console.WriteLine("Sent");
Sock.EndSend(AR);
}
public void RecieveCallBack(IAsyncResult AR)
{
Sock.EndReceive(AR);
Packet recPacket = new Packet(Buffer);
Console.WriteLine(recPacket.GetMessage());
Sock.BeginReceive(Buffer, 0, 255, SocketFlags.None, new AsyncCallback(RecieveCallBack), null);
}
}`
Solved
The error was in the send method which I didn't include.
sock.BeginSend(sentBuffer[0].Buffer, 0, sentBuffer[0].Buffer[0], SocketFlags.None, new AsyncCallback(SendCallBack), null);
sentBuffer is a list, to be a queue. I changed it to 255 and it workd
First of all, I just want to let you know that I am not new to programming, it should be easier to help me :)
I am having issues with my Multi-Threaded Chat that I am making in C# with Socket.
I have 3 threads :
void ListenSocketConnection : Check for Socket that could connect. Connected Socket are added into a List<>
void CheckIfClientStillConnectedThread : Check if a Socket disconnected. Disconnected Socket are removed from List<>
void ReceiveDataListener : Check if a Socket received data
Here is the issue. If the first or second thread remove a Socket from the List<>, the 'foreach (ClientManager cManager in clientsList)' will raise an exception.
Here is the second issue. If a socket disconnect during that foreach, 'foreach ClientManager cManager in clientsList)' will raise an exception : DisposedException
Do you have any tips on how I could fix this?
Here is my code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.ComponentModel;
using System.Threading;
namespace JAChat.Library
{
class SocketServer
{
private Socket socketServer;
private BackgroundWorker bwSocketConnectListener;
private BackgroundWorker bwCheckIfConnected;
private BackgroundWorker bwReceiveDataListener;
private List<ClientManager> clientsList;
#region Constructor
public SocketServer(int port)
{
clientsList = new List<ClientManager>();
socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socketServer.Bind(new IPEndPoint(IPAddress.Any, port));
socketServer.Listen(100);
bwSocketConnectListener = new BackgroundWorker();
bwSocketConnectListener.DoWork += new DoWorkEventHandler(ListenSocketConnection);
bwSocketConnectListener.RunWorkerAsync();
bwCheckIfConnected = new BackgroundWorker();
bwCheckIfConnected.DoWork += CheckIfClientStillConnectedThread;
bwCheckIfConnected.RunWorkerAsync();
bwReceiveDataListener = new BackgroundWorker();
bwReceiveDataListener.DoWork += ReceiveDataListener;
bwReceiveDataListener.RunWorkerAsync();
}
#endregion
#region Getter
public List<ClientManager> connectedClients
{
get
{
return clientsList;
}
}
#endregion
#region Public Methods
/// <summary>
/// Parse and send the command object to targets
/// </summary>
public void sendCommand(Command cmd)
{
BackgroundWorker test = new BackgroundWorker();
test.DoWork += delegate {
foreach(ClientManager cManager in clientsList){
cManager.sendCommand(cmd);
}
};
test.RunWorkerAsync();
}
/// <summary>
/// Disconnect and close the socket
/// </summary>
public void Disconnect()
{
socketServer.Disconnect(false);
socketServer.Close();
socketServer = null; //Stop some background worker
}
#endregion
#region Private Methods
private void ListenSocketConnection(object sender, DoWorkEventArgs e)
{
while (socketServer != null)
{
//Get and WAIT for new connection
ClientManager newClientManager = new ClientManager(socketServer.Accept());
clientsList.Add(newClientManager);
onClientConnect.Invoke(newClientManager);
}
}
private void CheckIfClientStillConnectedThread(object sender, DoWorkEventArgs e){
while(socketServer != null){
for(int i=0;i<clientsList.Count;i++){
if(clientsList[i].socket.Poll(10,SelectMode.SelectRead) && clientsList[i].socket.Available==0){
clientsList[i].socket.Close();
onClientDisconnect.Invoke(clientsList[i]);
clientsList.Remove(clientsList[i]);
i--;
}
}
Thread.Sleep(5);
}
}
private void ReceiveDataListener(object unused1, DoWorkEventArgs unused2){
while (socketServer != null){
foreach (ClientManager cManager in clientsList)
{
try
{
if (cManager.socket.Available > 0)
{
Console.WriteLine("Receive Data Listener 0");
//Read the command's Type.
byte[] buffer = new byte[4];
int readBytes = cManager.socket.Receive(buffer, 0, 4, SocketFlags.None);
Console.WriteLine("Receive Data Listener 1");
if (readBytes == 0)
break;
Console.WriteLine("Receive Data Listener 2");
CommandType cmdType = (CommandType)(BitConverter.ToInt32(buffer, 0));
Console.WriteLine("Receive Data Listener 3");
//Read the sender IP size.
buffer = new byte[4];
readBytes = cManager.socket.Receive(buffer, 0, 4, SocketFlags.None);
if (readBytes == 0)
break;
int senderIPSize = BitConverter.ToInt32(buffer, 0);
//Read the sender IP.
buffer = new byte[senderIPSize];
readBytes = cManager.socket.Receive(buffer, 0, senderIPSize, SocketFlags.None);
if (readBytes == 0)
break;
IPAddress cmdSenderIP = IPAddress.Parse(System.Text.Encoding.ASCII.GetString(buffer));
//Read the sender name size.
buffer = new byte[4];
readBytes = cManager.socket.Receive(buffer, 0, 4, SocketFlags.None);
if (readBytes == 0)
break;
int senderNameSize = BitConverter.ToInt32(buffer, 0);
//Read the sender name.
buffer = new byte[senderNameSize];
readBytes = cManager.socket.Receive(buffer, 0, senderNameSize, SocketFlags.None);
if (readBytes == 0)
break;
string cmdSenderName = System.Text.Encoding.Unicode.GetString(buffer);
//Read target IP size.
string cmdTarget = "";
buffer = new byte[4];
readBytes = cManager.socket.Receive(buffer, 0, 4, SocketFlags.None);
if (readBytes == 0)
break;
int targetIPSize = BitConverter.ToInt32(buffer, 0);
//Read the command's target.
buffer = new byte[targetIPSize];
readBytes = cManager.socket.Receive(buffer, 0, targetIPSize, SocketFlags.None);
if (readBytes == 0)
break;
cmdTarget = System.Text.Encoding.ASCII.GetString(buffer);
//Read the command's MetaData size.
string cmdMetaData = "";
buffer = new byte[4];
readBytes = cManager.socket.Receive(buffer, 0, 4, SocketFlags.None);
if (readBytes == 0)
break;
int metaDataSize = BitConverter.ToInt32(buffer, 0);
//Read the command's Meta data.
buffer = new byte[metaDataSize];
readBytes = cManager.socket.Receive(buffer, 0, metaDataSize, SocketFlags.None);
if (readBytes == 0)
break;
cmdMetaData = System.Text.Encoding.Unicode.GetString(buffer);
//Create the command object
Command cmd = new Command(cmdType, cmdSenderIP, cmdSenderName, IPAddress.Parse(cmdTarget), cmdMetaData);
this.onCommandReceived(cmd);
}
}
catch (ObjectDisposedException) {/*Le socket s'est déconnectée pendant le for each. Ignore l'érreur et retourne dans le while*/ }
catch (InvalidOperationException) { /* clientsList a été modifié pendant le foreach et délanche une exception. Retour while*/}
}
}
Console.WriteLine("Receive data listener closed");
}
#endregion
#region Events
public delegate void OnClientConnectEventHandler(ClientManager client);
/// <summary>
/// Events invoked when a client connect to the server
/// </summary>
public event OnClientConnectEventHandler onClientConnect = delegate { };
public delegate void OnClientDisconnectEventHandler(ClientManager client);
/// <summary>
/// Events invoked when a client disconnect from the server
/// </summary>
public event OnClientDisconnectEventHandler onClientDisconnect = delegate { };
public delegate void OnCommandReceivedEventHandler(Command cmd);
/// <summary>
/// Events invoked when a command has been sent to the server
/// </summary>
public event OnCommandReceivedEventHandler onCommandReceived = delegate { };
#endregion
}
}
There are multiple threads but I don't see any synchronization. That's incorrect. Use a lock to protect mutable shared state.
Instead of having this central management of all sockets, the polling and the checking of DataAvailable, why don't you just use either one thread per socket or async IO? That way you only ever manage one socket at a time. No polling necessary. You just call Read (or its async version) and wait for the data to arrive. This is a much better paradigm to deal with sockets. Basically, if your socket code contains DataAvailable or polling, you are going against best-practices (and likely have a bug somewhere). Think about how you would solve this without using the two. It is possible, and better.
In ReceiveDataListener you assume, that if data is available that an entire message is available. That's wrong because TCP is stream-oriented. You can receive the sent data in arbitrarily small chunks. Going with my point (2) fixes this.
To elaborate on (2): this is basically an actor model. One actor per socket. Whether you implement the actor using a thread, using async/await or using legacy async IO does not matter.
Hope this helps. Feel free to ask follow-up questions in the comments below.
The collection is being modified by multiple threads, so the count may very every time it is interrogated. As such, you should set it to a fixed amount; ie before the loop and then iterate through the list. Also, a count down rather than a count up is a better option since you are removing the elements.
Consider the following code :
private void CheckIfClientStillConnectedThread(object sender, DoWorkEventArgs e)
{
while (socketServer != null)
{
int count = clientsList.Count -1;
for (int i=count; i >= 0 ; i--)
{
if (clientsList[i].socket.Poll(10, SelectMode.SelectRead) && clientsList[i].socket.Available == 0)
{
clientsList[i].socket.Close();
onClientDisconnect.Invoke(clientsList[i]);
clientsList.Remove(clientsList[i]);
}
}
Thread.Sleep(5);
}
}
I wrote this code which sends an Image between sender and receiver.
First you must run receiver then run sender.
When I test this code on images between 1KB and 1.5KB, it works fine, but when I try to send a larger image, this message appears
cannot evaluate expression because a
native ..........
My code is below, can someone help?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.Threading;
namespace UPDTester
{
public class UDPClass
{
public Image Merge(Queue<byte[]> myList)
{
int ImgHeight = BitConverter.ToInt32(myList.Dequeue(), 0);
int ImgWidth = BitConverter.ToInt32(myList.Dequeue(), 0);
Bitmap bmp = new Bitmap(ImgWidth, ImgHeight);
Graphics g = Graphics.FromImage(bmp);
int x, y = 0;
while (myList.Count > 0)
{
x = BitConverter.ToInt32(myList.Dequeue(), 0);
y = BitConverter.ToInt32(myList.Dequeue(), 0);
g.DrawImage(ByteToBitmapConverter(myList.Dequeue()), x, y);
}
return bmp;
}
/// <summary>
/// Image Segmentatoin.
/// img: the image that we like to divided.
/// </summary>
public Queue<byte[]> Segmentation(Bitmap img)
{
Queue<byte[]> ByteArray = new Queue<byte[]>();
ByteArray.Enqueue(BitConverter.GetBytes(img.Width));
ByteArray.Enqueue(BitConverter.GetBytes(img.Height));
Image temimg;
for (ushort x = 0; x < img.Width - 5; x += 5)
{
for (ushort y = 0; y < img.Height - 5; y += 5)
{
//temimg = null;
temimg = img.Clone(new Rectangle(x, y, 5, 5), PixelFormat.Format32bppArgb);
ByteArray.Enqueue(BitConverter.GetBytes(x));
ByteArray.Enqueue(BitConverter.GetBytes(y));
ByteArray.Enqueue(ImageToByteConverter(temimg));
}
}
return ByteArray;
}
//Sender
public void SenderUDP(Bitmap img)
{
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string welcome = "Hello, are you there?";
data = Encoding.ASCII.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, ipep);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)sender;
data = new byte[1024];
int recv = server.ReceiveFrom(data, ref Remote);
MessageBox.Show("Message received from");
MessageBox.Show(Encoding.ASCII.GetString(data, 0, recv));
Queue<byte[]> temlist = Segmentation(img);
data = new byte[1024];
data =temlist.Dequeue();
//Send Width of image.
server.SendTo(data, data.Length, SocketFlags.None, ipep);
data = new byte[1024];
data = temlist.Dequeue();
//Send Height of image.
server.SendTo(data, data.Length, SocketFlags.None, ipep);
data = BitConverter.GetBytes(temlist.Count);
//Send Count of all list.
server.SendTo(data, data.Length, SocketFlags.None, ipep);
MessageBox.Show(temlist.Count.ToString() + " Iam Sender");
while (temlist.Count > 0)
{
server.SendTo(temlist.Dequeue(), Remote);
//MessageBox.Show(temlist.Count.ToString() + "S");
}
//server.Close();
}
//Receiver..(IP, PortNum)
public Image ReceiverUDP()
//public void ReceiverUDP(ref PictureBox pic)
{
int recv;
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
newsock.Bind(ipep);
MessageBox.Show("Waiting for a client....");
//Console.WriteLine("Waiting for a client....");
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)(sender);
recv = newsock.ReceiveFrom(data, ref Remote);
MessageBox.Show("Message received from ", Remote.ToString());
MessageBox.Show(Encoding.ASCII.GetString(data, 0, recv));
//Console.WriteLine("Message received from {0}:", Remote.ToString());
//Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
string welcome = "Welcome to my test server";
data = Encoding.ASCII.GetBytes(welcome);
newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
Queue<byte[]> TempList = new Queue<byte[]>();
//Receive Width of image.
newsock.ReceiveFrom(data, ref Remote);
TempList.Enqueue(data);
//Receive Height of image.
newsock.ReceiveFrom(data, ref Remote);
TempList.Enqueue(data);
//reccive Count of the list.
newsock.ReceiveFrom(data, ref Remote);
int count = BitConverter.ToInt32(data, 0);
MessageBox.Show(count.ToString() + " Iam Receiver");
data = new byte[1024];
while (count > 0)
{
data = new byte[1024];
newsock.ReceiveFrom(data, ref Remote);
TempList.Enqueue(data);
data = new byte[1024];
newsock.ReceiveFrom(data, ref Remote);
TempList.Enqueue(data);
data = new byte[1024];
newsock.ReceiveFrom(data, ref Remote);
TempList.Enqueue(data);
MessageBox.Show(count.ToString());
count -= 3;
}
return Merge(TempList);
}
private byte[] ImageToByteConverter(Image img)
{
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Png);
return ms.ToArray();
}
private Image ByteToBitmapConverter(byte[] buffer)
{
MemoryStream ms = new MemoryStream(buffer);
Image img = Image.FromStream(ms);
return img;
}
}
}
Most likely the reason it locks up is because UDP doesn't guarantee delivery. Packets can be dropped. If that happens, your receive loop is going to sit there waiting forever for a packet that won't ever come.
i have two Application to listen network Stream : Server.cs on the other hand; send file Client.cs. But i want to send more files on a stream from any folder. For example. i have C:/folder whish has got 3 jpg files. My client must run. Also My server.cs get files on stream:
Client.cs:
private void btn_send2_Click(object sender, EventArgs e)
{
string[] paths= null;
paths= System.IO.Directory.GetFiles(#"C:\folder" + #"\", "*.jpg", System.IO.SearchOption.AllDirectories);
byte[] Dizi;
TcpClient Gonder = new TcpClient("127.0.0.1", 51124);
FileStream Dosya;
FileInfo Dos;
NetworkStream Akis;
foreach (string path in paths)
{
Dosya = new FileStream(path , FileMode.OpenOrCreate);
Dos = new FileInfo(path );
Dizi = new byte[(int)Dos.Length];
Dosya.Read(Dizi, 0, (int)Dos.Length);
Akis = Gonder.GetStream();
Akis.Write(Dizi, 0, (int)Dosya.Length);
Gonder.Close();
Akis.Flush();
Dosya.Close();
}
}
Also i have Server.cs
void Dinle()
{
TcpListener server = null;
try
{
Int32 port = 51124;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
server = new TcpListener(localAddr, port);
server.Start();
Byte[] bytes = new Byte[1024 * 250000];
// string ReceivedPath = "C:/recieved";
while (true)
{
MessageBox.Show("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
MessageBox.Show("Connected!");
NetworkStream stream = client.GetStream();
if (stream.CanRead)
{
saveFileDialog1.ShowDialog();
// burası degişecek
string pathfolder = saveFileDialog1.FileName;
StreamWriter yaz = new StreamWriter(pathfolder);
string satir;
StreamReader oku = new StreamReader(stream);
while ((satir = oku.ReadLine()) != null)
{
satir = satir + (char)13 + (char)10;
yaz.WriteLine(satir);
}
oku.Close();
yaz.Close();
client.Close();
}
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
Please look Client.cs: icollected all files from "c:\folder"
paths= System.IO.Directory.GetFiles(#"C:\folder" + #"\", "*.jpg", System.IO.SearchOption.AllDirectories);
My Server.cs how to get all files from stream?
It's not a typical way of doing things.
Usually you would write a single file in a single stream and repeat the process for multiple files. You risk data corruption this way as you'll have to place some kind of marker in the stream to know where to split it.
The easiest way is to use multiple sockets, one for commands and one (or more) for sending files.
The below code have NOT been tested, just wrote it up to show what I mean. It's multithreaded and can receive multiple files from the same client, just call sendfiles multiple times in the client.
You might want to add error/exception handling if you decide to finish the code.
Server.cs
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Test2
{
public class Server
{
private readonly TcpListener _listener = new TcpListener(1234);
public void Start()
{
_listener.BeginAcceptTcpClient(OnClient, null);
}
private void OnClient(IAsyncResult ar)
{
// End async accept and start wait for a new connection again
TcpClient client = _listener.EndAcceptTcpClient(ar);
_listener.BeginAcceptTcpClient(OnClient, null);
// Let's start receiving files from the accepted client.
var context = new Context {Client = client, Buffer = new byte[8196]};
client.GetStream().BeginRead(context.Buffer, 0, context.Buffer.Length, OnReceive, context);
}
/// <summary>
/// Got some stuff from a client
/// </summary>
/// <param name="ar"></param>
private void OnReceive(IAsyncResult ar)
{
// got a file command
var context = (Context) ar.AsyncState;
int bytesRead = context.Client.GetStream().EndRead(ar);
string cmd = Encoding.UTF8.GetString(context.Buffer, 0, bytesRead);
string[] parts = cmd.Split(';');
string command = parts[0];
// want to send another file
if (command == "sendfile")
{
// context info for receiving files
var client = new FileClient();
client.FileName = parts[1];
client.Size = long.Parse(parts[2]);
client.FileStream = new FileStream("C:\\" + client.FileName, FileMode.CreateNew, FileAccess.Write);
// startup listener where we are going to receive the file.
var listener = new TcpListener(IPAddress.Any, 0); // get a kernelassigned number
client.Listener = listener;
listener.Start();
listener.BeginAcceptTcpClient(OnFileSocket, client);
// send reply
var ep = (IPEndPoint) listener.LocalEndpoint;
byte[] reply = Encoding.UTF8.GetBytes(ep.Port.ToString());
context.Client.GetStream().Write(reply, 0, reply.Length);
}
}
// Receiving the actual files.
private void OnFileSocket(IAsyncResult ar)
{
var client = (FileClient) ar.AsyncState;
client.Socket = client.Listener.EndAcceptTcpClient(ar);
var buffer = new byte[8192];
client.Buffer = buffer;
client.Socket.GetStream().BeginRead(buffer, 0, buffer.Length, OnReceiveFile, client);
}
private void OnReceiveFile(IAsyncResult ar)
{
var client = (FileClient) ar.AsyncState;
int bytesRead = client.Socket.GetStream().EndRead(ar);
client.Received += bytesRead;
client.FileStream.Write(client.Buffer, 0, bytesRead);
// recieved complete file, disconnect and exit.
if (client.Received == client.Size)
{
client.FileStream.Close();
client.Socket.Close();
return;
}
client.Socket.GetStream().BeginRead(client.Buffer, 0, client.Buffer.Length, OnReceiveFile, client);
}
#region Nested type: Context
private class Context
{
public byte[] Buffer;
public TcpClient Client;
}
#endregion
#region Nested type: FileClient
private class FileClient
{
public byte[] Buffer;
public string FileName;
public FileStream FileStream;
public TcpListener Listener;
public long Received;
public long Size;
public TcpClient Socket;
}
#endregion
}
}
Client.cs
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Test2
{
internal class Client
{
private readonly IPAddress _server;
private readonly TcpClient _tcpClient = new TcpClient();
public Client(IPAddress server)
{
_server = server;
_tcpClient = new TcpClient();
}
public void Connect()
{
_tcpClient.Connect(new IPEndPoint(_server, 1234));
}
// asks server on which port the file should be sent.
private int RequestPort(string fileName, long length)
{
// lock tpcClient for each request, so we dont mix up the responses.
lock (_tcpClient)
{
// send request
byte[] bytes = Encoding.UTF8.GetBytes("sendfile;" + fileName + ";" + length);
_tcpClient.GetStream().Write(bytes, 0, bytes.Length);
// get reply
var buffer = new byte[1024];
int bytesRead = _tcpClient.GetStream().Read(buffer, 0, buffer.Length);
string reply = Encoding.UTF8.GetString(buffer, 0, bytesRead);
// error message or port?
int port;
if (!int.TryParse(reply, out port))
throw new InvalidOperationException("Server sent an error:" + reply);
return port;
}
}
public void SendFiles(string[] fileNames)
{
// Use a buffer to not preserve memory (instead of reading whole file into memory)
var buffer = new byte[8192];
foreach (string fileName in fileNames)
{
using (var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
// Send on commandchannel that we want to send a file.
int filePort = RequestPort(Path.GetFileName(fileName), fileStream.Length);
var client = new TcpClient(new IPEndPoint(_server, filePort));
NetworkStream stream = client.GetStream();
// repeat until there are no more bytes to read.
int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
while (bytesRead > 0)
{
stream.Write(buffer, 0, bytesRead);
bytesRead = fileStream.Read(buffer, 0, buffer.Length);
}
stream.Close();
client.Close();
}
}
}
}
}