I’m using this client/server code which i found on the net for communication:
client:
public void Send(string name, string path)
{
try
{
IPAddress[] ipAddress = Dns.GetHostAddresses("address");
IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
string fileName = "somefile";
string filePath = path;
byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);
byte[] fileData = File.ReadAllBytes(System.IO.Path.Combine(filePath, fileName));
byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
clientSock.Connect(ipEnd);
clientSock.Send(clientData);
MessageBox.Show("file has been send: " + fileName);
clientSock.Close();
}
catch (Exception ex)
{
Console.WriteLine("File Sending fail." + ex.Message);
}
}
server:
public void Receive()
{
try
{
lblInfo.Content = "That program can transfer small file. I've test up to 850kb file";
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 5656);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
sock.Listen(100);
Socket clientSock = sock.Accept();
// 1024 * 25.000 = 25mb max that can be received at once with this program.
byte[] clientData = new byte[1024 * 25000];
string receivedPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\";
int receivedBytesLen = clientSock.Receive(clientData);
int fileNameLen = BitConverter.ToInt32(clientData, 0);
string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);
lblInfo.Content = "Client: connected & File started received.";
BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + fileName, FileMode.Append)); ;
bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);
lblInfo.Content = "File: received & saved at path: " + receivedPath;
bWrite.Close();
clientSock.Close();
}
catch (Exception ex)
{
lblInfo.Content = "File Receiving fail." + ex.Message;
}
}
this code works fine for 1 client that transferes a file to the server. i was wondering how i can change this code to make it communicate with multiple clients that can send files to the server?
also, the server code ‘hangs’ at Socket clientSock = sock.Accept(); and waits untill it receives something. It would be nice if there is a ‘listener’ that listens for new incomming files and then loop through the code, instead of endless waiting at that line.
Im new to client/server programming and all ears to other suggestions.
Here you have explanations for creating your loops for new connections :
http://msdn.microsoft.com/en-us/library/dz10xcwh.aspx