C# Multi threaded Server - c#

I have this client and server code.
Client:
namespace ClientTest
{
internal class Program
{
private static TcpClient client;
private static NetworkStream stream;
private static void Main(string[] args)
{
string temp;
client = new TcpClient("192.168.1.2",5052);
stream = client.GetStream();
Console.WriteLine(client.SendBufferSize);
while ((temp = Console.ReadLine()) != "exit")
{
Send(temp);
}
Thread one=new Thread(()=> SendFile(new FileInfo(#"1.doc")));
one.Start();
Thread two=new Thread(()=> SendFile(new FileInfo(#"2.docx")));
two.Start();
// Console.ReadKey(true);
}
public static void SendFile(FileInfo file)
{
stream = client.GetStream();
byte[] id = BitConverter.GetBytes((ushort)1);
byte[] size = BitConverter.GetBytes(file.Length);
byte[] fileName = Encoding.UTF8.GetBytes(file.Name);
byte[] fileNameLength = BitConverter.GetBytes((ushort)fileName.Length);
byte[] fileInfo = new byte[12 + fileName.Length];
id.CopyTo(fileInfo, 0);
size.CopyTo(fileInfo, 2);
fileNameLength.CopyTo(fileInfo, 10);
fileName.CopyTo(fileInfo, 12);
stream.Write(fileInfo, 0, fileInfo.Length); //Размер файла, имя
byte[] buffer = new byte[1024 * 32];
int count;
long sended = 0;
using (FileStream fileStream = new FileStream(file.FullName, FileMode.Open))
while ((count = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, count);
sended += count;
Console.WriteLine("{0} bytes sended.", sended);
}
stream.Flush();
}
private static void Send(string message)
{
byte[] id = BitConverter.GetBytes((ushort)0);
byte[] msg = Encoding.UTF8.GetBytes(message);
byte[] msgLength = BitConverter.GetBytes((ushort)msg.Length);
byte[] fileInfo = new byte[12 + msg.Length];
id.CopyTo(fileInfo, 0);
msgLength.CopyTo(fileInfo, 10);
msg.CopyTo(fileInfo, 12);
stream.Write(fileInfo, 0, fileInfo.Length);
stream.Flush();
}
}
}
Server:
namespace Server_Test
{
class Server
{
static void Main(string[] args)
{
Server serv = new Server();
}
private TcpListener listener { get; set; }
private NetworkStream stream { get; set; }
public Server()
{
listener = new TcpListener(IPAddress.Parse("192.168.1.2"), 5052);
listener.Start();
new Thread(ListenForClients).Start();
}
private void ListenForClients()
{
while (true)
{
TcpClient client = this.listener.AcceptTcpClient();
new Thread(HandleClient).Start(client);
}
}
private void HandleClient(object tcpClient)
{
TcpClient client = (TcpClient)tcpClient;
while (client.Connected)
{
Recieve(client);
}
}
private void Recieve(TcpClient client)
{
byte[] buffer = new byte[client.ReceiveBufferSize];
try
{
stream = client.GetStream();
int bytesRead = stream.Read(buffer, 0, 12);
if (bytesRead == 0) return;
ushort id = BitConverter.ToUInt16(buffer, 0);
long len = BitConverter.ToInt64(buffer, 2);
ushort nameLen = BitConverter.ToUInt16(buffer, 10);
stream.Read(buffer, 0, nameLen);
string fileName = Encoding.UTF8.GetString(buffer, 0, nameLen);
if (id == 1)
{
using (BinaryWriter writer = new BinaryWriter(new FileStream(fileName, FileMode.Create)))
{
int recieved = 0;
while (recieved < len)
{
bytesRead = stream.Read(buffer, 0, client.ReceiveBufferSize);
recieved += bytesRead;
writer.Write(buffer, 0, bytesRead);
Console.WriteLine("{0} bytes recieved.", recieved);
}
}
Console.WriteLine("File length: {0}", len);
Console.WriteLine("File Name: {0}", fileName);
Console.WriteLine("Recieved!");
}
else
{
Console.WriteLine(fileName);
}
}
catch (Exception ex)
{
stream.Close();
client.Close();
Console.WriteLine(ex);
}
finally
{
stream.Flush();
}
}
}
}
The problem:i can't send 2 files in threads. If i send 1 file, server receives it and correctly saves.
What changes needed in this code to let client transfer 2 or more files and to let server receive it?
UDP. Added modified SendFile, but in doesn't work.
public static void SendFile(FileInfo file)
{
TcpClient client;
NetworkStream stream;
client = new TcpClient("192.168.1.2", 5052);
stream = client.GetStream();
byte[] id = BitConverter.GetBytes((ushort)1);
byte[] size = BitConverter.GetBytes(file.Length);
byte[] fileName = Encoding.UTF8.GetBytes(file.Name);
byte[] fileNameLength = BitConverter.GetBytes((ushort)fileName.Length);
byte[] fileInfo = new byte[12 + fileName.Length];
id.CopyTo(fileInfo, 0);
size.CopyTo(fileInfo, 2);
fileNameLength.CopyTo(fileInfo, 10);
fileName.CopyTo(fileInfo, 12);
stream.Write(fileInfo, 0, fileInfo.Length); //Размер файла, имя
byte[] buffer = new byte[1024 * 32];
int count;
long sended = 0;
using (FileStream fileStream = new FileStream(file.FullName, FileMode.Open))
while ((count = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, count);
sended += count;
Console.WriteLine("{0} bytes sended.", sended);
}
}

On the client side, your two separate sending threads cannot share the same instance of client = new TcpClient("192.168.1.2",5052); to simultaneously send data. Each thread should have its own instance. Note, however, that it is fine for 2 client sockets to hit the same server-side IP:port simultaneously. It is just that the outbound port on the client-side has to be different between the 2 connections. When you create an additional outbound TCP connection on the client, the TcpClient will automatically use the next available outbound port.
For example, you could try something like the following:
internal class Program
{
private static void Main(string[] args)
{
SenderThreadClass stc1 = SenderThreadClass("192.168.1.2", 5052);
SenderThreadClass stc2 = SenderThreadClass("192.168.1.2", 5052);
Thread one = new Thread(()=> stc1.SendFile(new FileInfo(#"1.doc")));
one.Start();
Thread two = new Thread(()=> stc2.SendFile(new FileInfo(#"2.docx")));
two.Start();
}
}
public class SenderThreadClass
{
private TcpClient client;
private NetworkStream stream;
public SenderThreadClass(string serverIP, int serverPort)
{
client = new TcpClient(serverIP, serverPort);
stream = client.GetStream();
}
public void SendFile(FileInfo file)
{
byte[] id = BitConverter.GetBytes((ushort)1);
byte[] size = BitConverter.GetBytes(file.Length);
byte[] fileName = Encoding.UTF8.GetBytes(file.Name);
byte[] fileNameLength = BitConverter.GetBytes((ushort)fileName.Length);
byte[] fileInfo = new byte[12 + fileName.Length];
id.CopyTo(fileInfo, 0);
size.CopyTo(fileInfo, 2);
fileNameLength.CopyTo(fileInfo, 10);
fileName.CopyTo(fileInfo, 12);
stream.Write(fileInfo, 0, fileInfo.Length); //Размер файла, имя
byte[] buffer = new byte[1024 * 32];
int count;
long sended = 0;
using (FileStream fileStream = new FileStream(file.FullName, FileMode.Open))
while ((count = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, count);
sended += count;
Console.WriteLine("{0} bytes sended.", sended);
}
stream.Flush();
}
}

Related

How To Send A File By Sockets On TCP Protocol In C#?

I have a serious problem with this code. This is how it should work:
Client connects to server and choose a file on disk. after that client sends a (byte[] buffer) to the server by this format("File" (4 bytes) + FileNameLength (4 bytes) + FileDataLength (4 bytes)).
After that server creates a (byte[] buffer) with this size (new byte[FileNameLength + FileDataLength]).So client sends a data to the server by this format(byte[] buffer = FileName + FileData). And the server gets a file. The problem is here that i have a MessageBox in the Server to see the FileName after receiving that but MessageBox is always blank and it runs times and times and times.
what's the solution?
The Server:
private Socket SServer = null;
private Socket SClient = null;
private byte[] buffer = new byte[1024];
private byte[] FileNameLength = null;
private byte[] FileSize = null;
private void Server_Load(object sender, EventArgs e)
{
SServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SServer.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 13000));
SServer.Listen(1);
new Thread(() =>
{
SClient = SServer.Accept();
MessageBox.Show("Connected.");
new Thread(() => Receiver()).Start();
}).Start();
}
private void Receiver()
{
buffer = new byte[1024];
while (true)
{
Int32 AllLength = SClient.Receive(buffer, 0, buffer.Length, SocketFlags.None);
byte[] Devider = new byte[4];
Array.Copy(buffer, 0, Devider, 0, 4);
string Devide = Encoding.ASCII.GetString(Devider);
if (AllLength > 0)
{
if (Devide == "File")
{
FileNameLength = new byte[4];
Array.Copy(buffer, 4, FileNameLength, 0, 4);
FileSize = new byte[4];
Array.Copy(buffer, 8, FileSize, 0, 4);
buffer = null;
buffer = new byte[BitConverter.ToInt32(FileNameLength, 0) + BitConverter.ToInt32(FileSize, 0)];
}
else
{
byte[] FileNameBytes = new byte[BitConverter.ToInt32(FileNameLength, 0)];
Array.Copy(buffer, 0, FileNameBytes, 0, BitConverter.ToInt32(FileNameLength, 0));
byte[] FileBytes = new byte[BitConverter.ToInt32(FileSize, 0)];
Array.Copy(buffer, BitConverter.ToInt32(FileNameLength, 0), FileBytes, 0, BitConverter.ToInt32(FileBytes, 0));
string FileName = Encoding.ASCII.GetString(FileNameBytes);
MessageBox.Show(FileName);
buffer = null;
buffer = new byte[1024];
}
}
}
}
TheClient:
private Socket SClient = null;
string Path, FileName;
private void Client_Load(object sender, EventArgs e)
{
SClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SClient.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 13000));
}
private void BT_SendFile_Click(object sender, EventArgs e)
{
byte[] FileLengthBytes = BitConverter.GetBytes(FileName.Length);
byte[] FileBytes = File.ReadAllBytes(Path + FileName);
byte[] buffer = new byte[FileLengthBytes.Length + FileBytes.Length + 4];
//buffer = Encoding.Unicode.GetBytes("File") + FileLengthBytes + FileBytes;
Array.Copy(Encoding.ASCII.GetBytes("File"), 0, buffer, 0, 4);
Array.Copy(FileLengthBytes, 0, buffer, 4, FileLengthBytes.Length);
Array.Copy(BitConverter.GetBytes(FileBytes.Length), 0, buffer, 8, 4);
SClient.Send(buffer, 0, buffer.Length, SocketFlags.None);
byte[] FileNameBytes = Encoding.ASCII.GetBytes(FileName);
buffer = null;
buffer = new byte[FileNameBytes.Length + FileBytes.Length];
Array.Copy(FileNameBytes, 0, buffer, 0, FileNameBytes.Length);
Array.Copy(FileBytes, 0, buffer, FileNameBytes.Length, FileBytes.Length);
SClient.Send(buffer, 0, buffer.Length, SocketFlags.None);
}
private void BT_Browse_Click(object sender, EventArgs e)
{
OpenFileDialog N = new OpenFileDialog();
if (N.ShowDialog() == DialogResult.OK)
{
TB_Address.Text = N.FileName;
string[] Seperate = N.FileName.Split('\\');
FileName = Seperate[Seperate.Length - 1];
Path = null;
foreach (string str in Seperate)
{
if (str != Seperate[Seperate.Length - 1])
Path += str + "\\";
}
}
}
as this friend (Fildor) said, i try to read more about the protocols.
thank you two guys but i think if i separate the file and send it pieces by pieces, i can send the hole file.
I know maybe this is stupid but i think it works.

The magic number in gzip header is not correct

Task: there are 2 clients. They must compress byte array, send it, receive byte array, decompress it and do something with result.
I use TCP for sending and receiving.
The error arises in the decompress method.
Sending method:
private static void AsiooutOnAudioAvailable(object sender, AsioAudioAvailableEventArgs e)
{
audio = SamplesToBytes(monoSamples);
byte[] compressedBytes = CompressBytes(audio);
if (_isConnected)
{
Task.Run(() => _receiver.BeginSend(compressedBytes, 0, compressedBytes.Length, SocketFlags.None, SendCallback, null));
}
}
Receiving:
private static void Receive()
{
_receiver.BeginReceive(incomingBytes, 0, incomingBytes.Length, SocketFlags.None, ReceiveCallback, null);
}
private static void ReceiveCallback(IAsyncResult ar)
{
int receivedBytesCount = _receiver.EndReceive(ar);
byte[] _audio = new byte[receivedBytesCount];
for (int i = 0; i < receivedBytesCount; i++)
{
_audio[i] = incomingBytes[i];
}
var decompressBytes = DecompressBytes(_audio);
_incomingBuffer.AddSamples(decompressBytes, 0, decompressBytes.Length);
Receive();
}
Compression and decompression
public static byte[] CompressBytes(byte[] bytes)
{
using (MemoryStream output = new MemoryStream())
{
using (GZipStream gzip = new GZipStream(output, CompressionMode.Compress))
{
gzip.Write(bytes, 0, bytes.Length);
}
return output.ToArray();
}
}
static byte[] DecompressBytes(byte[] gzip)
{
using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress))
{
int size = gzip.Length;
byte[] buffer = new byte[size];
using (MemoryStream memory = new MemoryStream())
{
int count = 0;
do
{
count = stream.Read(buffer, 0, size); //error place
if (count > 0)
{
memory.Write(buffer, 0, count);
}
}
while (count > 0);
return memory.ToArray();
}
}
}

Why is this way of reading from a NetworkStream so much faster?

At my company we've run into an issue that we cannot seem to explain. We're reading from a NetworkStream using a buffer of 2048 bytes. When both the client and server use that buffersize to write and read with, it's hideously slow (1 second extra on top of other processing times). If we use a buffersize that's very large, like 32k everything works really fast. The message we're sending is usually much larger than 32k so the entire message does not entirely fit in that buffer. The way we're reading is shown in the code below in the HandleDataLargeBuffer method.
To build a testcase for this issue I've written the code below, and I've posted my output below that.
My questions:
Any idea why a larger buffer size would be faster (less read calls but those shouldn't take too much time)?
In the code below, HandleDataVariableBuffer is much much faster than the other methods of reading, why?
Which is the best way of reading anyway?
Using a Proxy class to simulate slowdowns, pasted below the main file.
class Program
{
private StreamWriter Writer;
private int Count = 0;
static void Main(string[] args)
{
new Program();
}
public Program()
{
Writer = new StreamWriter(new FileStream("C:\\test.txt", FileMode.Create));
Start();
}
public void Start()
{
Proxy p = new Proxy();
new Thread(p.Start).Start();
Thread.Sleep(500);
new Thread(SetupServer).Start();
Thread.Sleep(1000); // Wait for TCP Server setup.
for (int i = 0; i != 3; ++i)
{
TcpClient client = new TcpClient("127.0.0.1", 50001);
Send(client.GetStream());
client.Close();
Thread.Sleep(1000);
}
WriteLine("Tests done.");
Console.ReadLine();
Writer.Close();
}
private void SetupServer()
{
WriteLine("[Server] Starting server.");
TcpListener listener = new TcpListener(IPAddress.Any, 50000);
listener.Start();
WriteLine("[Server] Started listening on port 50000.");
while (true) // We'll just forcibly end, obviously you'd use the callback methods for this normally.
{
TcpClient client = listener.AcceptTcpClient();
WriteLine(String.Format("[Server] Accepted client with IP: {0}", client.Client.RemoteEndPoint.ToString()));
new Thread(HandleClient).Start(client);
}
}
private void HandleClient(object argument)
{
TcpClient client = (TcpClient)argument;
NetworkStream stream = client.GetStream();
// Now there are multiple ways to handle this data, however first we read the int at the start.
byte[] length = new byte[4];
stream.Read(length, 0, 4);
int lengthInt = BitConverter.ToInt32(length, 0);
if (lengthInt <= 0) return; // Shouldn't happen.
// Test data read in multiple ways.
Stopwatch watch = new Stopwatch();
watch.Start();
string handler = "";
if (Count == 0)
{
handler = "LargeBuffer";
HandleDataLargeBuffer(lengthInt, stream);
++Count;
}
else if (Count == 1)
{
handler = "SmallBuffer";
HandleDataSmallBuffer(lengthInt, stream);
++Count;
}
else if (Count == 2)
{
handler = "VariableBuffer";
HandleDataVariableBuffer(lengthInt, stream);
Count = 0;
}
watch.Stop();
WriteLine(String.Format("\t[Server] [{3}] Read {0} bytes from client {1} in {2} ms", lengthInt.ToString(), client.Client.RemoteEndPoint.ToString(), watch.ElapsedMilliseconds.ToString(), handler));
}
private void HandleDataLargeBuffer(int length, NetworkStream stream)
{
int read = 0;
int totalRead = 0;
MemoryStream dataBuffer = new MemoryStream(); // I'm writing to a memory stream because in my real life situation I write (stream) to another NetworkStream
byte[] buffer = new byte[8192 * 4];
while ((read = stream.Read(buffer, 0, 8192 * 4)) != 0 && totalRead < length)
{
totalRead += read;
dataBuffer.Write(buffer, 0, read);
}
}
private void HandleDataSmallBuffer(int length, NetworkStream stream)
{
int read = 0;
int totalRead = 0;
MemoryStream dataBuffer = new MemoryStream(); // I'm writing to a memory stream because in my real life situation I write (stream) to another NetworkStream
byte[] buffer = new byte[512];
while ((read = stream.Read(buffer, 0, 512)) != 0 && totalRead < length)
{
totalRead += read;
dataBuffer.Write(buffer, 0, read);
}
}
private void HandleDataVariableBuffer(int length, NetworkStream stream)
{
int read = 0;
int totalRead = 0;
MemoryStream dataBuffer = new MemoryStream(); // I'm writing to a memory stream because in my real life situation I write (stream) to another NetworkStream
while (totalRead < length)
{
byte[] buffer = new byte[length - totalRead]; // You'd obviously do some additional checks on 'length' to make sure no foul play is involved.
read = stream.Read(buffer, 0, length - totalRead);
totalRead += read;
dataBuffer.Write(buffer, 0, read);
}
}
public void Send(NetworkStream stream)
{
// Generate some random data
Random r = new Random();
byte[] buf = new byte[1024 * 420]; // Buffer of 420k to simulate a decently large message
byte[] length = BitConverter.GetBytes(1024 * 420);
r.NextBytes(buf);
// Create the total message array: [Length][Message]
byte[] totalMessage = new byte[4 + 1024 * 420];
System.Buffer.BlockCopy(length, 0, totalMessage, 0, 4);
System.Buffer.BlockCopy(buf, 0, totalMessage, 4, buf.Length);
// Use a memory stream for ease of use
Stopwatch watch = new Stopwatch();
watch.Start();
using (MemoryStream memStream = new MemoryStream(totalMessage))
{
int read = -1;
byte[] buffer = new byte[8192];
while ((read = memStream.Read(buffer, 0, 8192)) != 0)
{
stream.Write(buffer, 0, read);
}
}
stream.Flush();
watch.Stop();
WriteLine("[Send] Took " + watch.ElapsedMilliseconds + " ms to send " + totalMessage.Length + " bytes of data.");
}
public void WriteLine(string str)
{
Writer.WriteLine(str);
Writer.Flush();
}
}
Proxy.cs
public class Proxy
{
public void Start()
{
TcpListener listener = new TcpListener(IPAddress.Any, 50001);
listener.Start();
while (true)
{
TcpClient client = listener.AcceptTcpClient();
new Thread(HandleClient).Start(client);
}
}
private void HandleClient(object argument)
{
TcpClient client = (TcpClient)argument;
Thread.Sleep(1000);
NetworkStream clientStream = client.GetStream();
int read = 0;
byte[] length = new byte[4];
clientStream.Read(length, 0, 4);
int lengthInt = BitConverter.ToInt32(length, 0);
if (lengthInt <= 0)
{
client.Close();
return;
}
TcpClient serverClient = new TcpClient("127.0.0.1", 50000);
NetworkStream serverStream = serverClient.GetStream();
int totalRead = 0;
serverStream.Write(length, 0, 4);
while (totalRead < lengthInt)
{
Thread.Sleep(50);
byte[] buffer = new byte[lengthInt - totalRead]; // You'd obviously do some additional checks on 'length' to make sure no foul play is involved.
read = clientStream.Read(buffer, 0, lengthInt - totalRead);
totalRead += read;
serverStream.Write(buffer, 0, read);
}
serverStream.Flush();
Thread.Sleep(1000);
client.Close();
serverClient.Close();
}
}
I'm sorry for the heap of code posted, when I first started I hoped it'd be smaller. Here's the output on my machine.
[Server] Starting server.
[Server] Started listening on port 50000.
[Server] Accepted client with IP: 127.0.0.1:3985
[Send] Took 1047 ms to send 430084 bytes of data.
[Server] [LargeBuffer] Read 430080 bytes from client 127.0.0.1:3985 in 1148 ms
[Server] Accepted client with IP: 127.0.0.1:3987
[Send] Took 1049 ms to send 430084 bytes of data.
[Server] [SmallBuffer] Read 430080 bytes from client 127.0.0.1:3987 in 1150 ms
[Server] Accepted client with IP: 127.0.0.1:3989
[Send] Took 1051 ms to send 430084 bytes of data.
[Server] [VariableBuffer] Read 430080 bytes from client 127.0.0.1:3989 in 100 ms
Tests done.

How to transfer pdf file correctly with socket programming in C#?

I am transferring file via socket programming in C# with the code given below. But when I take pdf as input file, it is not received correctly. I have seen sent and received files in notepad, they are not same.
I am not able to figure it out. any help appreciated !!!
Server Code:
class ConnectionInfo
{
public Socket Socket;
public byte[] Buffer;
public int client;
public string fileName;
}
class Program
{
static int chunkSize = 16 * 1024;
static int chucksizeWithoutHeaderData = chunkSize - 8;
static List<ConnectionInfo> list = new List<ConnectionInfo>();
static Socket serverSocket;
static int nClient = 0;
static void AcceptCallback(IAsyncResult result)
{
ConnectionInfo info = new ConnectionInfo();
info.Socket = serverSocket.EndAccept(result);
info.Buffer = new byte[chunkSize * 4];
Console.WriteLine("Client connected");
nClient++;
info.client = nClient;
list.Add(info);
info.Socket.BeginReceive(info.Buffer, 0, info.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), info);
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
static void ReceiveCallBack(IAsyncResult result)
{
ConnectionInfo info = result.AsyncState as ConnectionInfo;
try
{
Int32 nSegmentNumber = BitConverter.ToInt32(info.Buffer, 0);
Int32 nMaxSegment = BitConverter.ToInt32(info.Buffer, 4);
string strFileName = string.Format(#"D:\xyz.pdf", info.client);
//int bySize = info.Socket.EndReceive(result);
int bySize = 0;
try
{
bySize = info.Socket.EndReceive(result);
}
catch (Exception ex)
{
Console.WriteLine("Error from client {0}: {1}", info.client, ex.Message);
return;
}
if (bySize <= 0)
{
return;
}
using (FileStream fs = new FileStream(strFileName, FileMode.OpenOrCreate))
{
Console.WriteLine("Received segment {0} of {1} from client {2}", nSegmentNumber, nMaxSegment, info.client);
fs.Position = fs.Length;
fs.Write(info.Buffer, 8, bySize - 8);
Console.Write("Content in FILE: " + Encoding.ASCII.GetString(info.Buffer));
if (nSegmentNumber >= nMaxSegment)
{
Console.WriteLine("Completed receipt from client {0}", info.client);
}
}
info.Socket.BeginReceive(info.Buffer, 0, info.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), info);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
static void Main(string[] args)
{
try
{
Console.WriteLine("Server");
IPAddress address = IPAddress.Parse("127.0.0.1"); //The IP address of the server
IPEndPoint myEndPoint = new IPEndPoint(address, 6503);
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(myEndPoint);
serverSocket.Listen(1000);
Console.WriteLine("Press enter to end server");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.ReadLine();
}
}
}
Client code:
class Program
{
static TcpClient socket = new TcpClient();
static int chunkSize = 16 * 1024;
static int chucksizeWithoutHeaderData = chunkSize - 8;
static byte[] byReceiveBuffer = new byte[chunkSize * 4];
static void ReceiveCallBack(IAsyncResult result)
{
Socket socket = result.AsyncState as Socket;
try
{
int bySize = socket.EndReceive(result);
Console.WriteLine("Recieved bytes {0}", bySize);
if (bySize != 0)
{
Int32 nSegmentNumber = BitConverter.ToInt32(byReceiveBuffer, 0);
Int32 nMaxSegment = BitConverter.ToInt32(byReceiveBuffer, 4);
Console.WriteLine("Received segment {0} of {1}", nSegmentNumber, nMaxSegment);
string strFileName = string.Format(#"c:\temp\client-from-server.dat");
using (FileStream fs = new FileStream(strFileName, FileMode.OpenOrCreate))
{
fs.Position = fs.Length;
fs.Write(byReceiveBuffer, 8, bySize - 8);
}
if (nSegmentNumber >= nMaxSegment)
{
Console.WriteLine("all done");
}
}
socket.BeginReceive(byReceiveBuffer, 0, byReceiveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
static void Main(string[] args)
{
Console.WriteLine("Press enter to go");
Console.ReadLine();
socket.Connect("127.0.0.1", 6503);
Console.WriteLine("Client");
Console.ReadLine();
string filePath = "";
string fileName = "C:\\abc.pdf";
//fileName = fileName.Replace("\\", "/");
while (fileName.IndexOf("\\") > -1)
{
filePath += fileName.Substring(0, fileName.IndexOf("\\") + 1);
fileName = fileName.Substring(fileName.IndexOf("\\") + 1);
}
byte[] byBuffer;
using (FileStream fs = new FileStream(#filePath+fileName, FileMode.Open, FileAccess.Read, FileShare.None))
{
using (BinaryReader br = new BinaryReader(fs))
{
int nMaxChunk = 0;
int nCurrentChunk = 0;
nMaxChunk = (int)(fs.Length / chucksizeWithoutHeaderData);
if ((nMaxChunk * chucksizeWithoutHeaderData) < fs.Length)
{
++nMaxChunk;
}
byte[] byMaxChunk = BitConverter.GetBytes(nMaxChunk);
Int64 nAmount = 0;
while (fs.Length > nAmount)
{
++nCurrentChunk;
byte[] byCurrentChunk = BitConverter.GetBytes(nCurrentChunk);
byBuffer = br.ReadBytes(chucksizeWithoutHeaderData);
Console.WriteLine("Sending {0}bytes, chunk {1} of {2}", byBuffer.Length, nCurrentChunk, nMaxChunk);
byte[] byTransmitBuffer = new byte[byBuffer.Length + 8];
Array.Copy(byCurrentChunk, byTransmitBuffer, 4);
Array.Copy(byMaxChunk, 0, byTransmitBuffer, 4, 4);
Array.Copy(byBuffer, 0, byTransmitBuffer, 8, byBuffer.Length);
socket.Client.Send(byTransmitBuffer);
nAmount += byBuffer.Length;
}
}
}
socket.Client.Disconnect(false);
Console.WriteLine("done");
Console.ReadLine();
}
}

Delay 3mins at the start of the program why? socket programming in C#

I will get 3mins of delay at the start of the below program.but where as in hyper terminal it shows every data for every 2 secs.
Her is my below code.please let me know where i went wrong .How i can rectify this delay. any suggestion?
private void StartReceiving()
{
// coding part of receiving changed.
try
{
string IPStr = textBox1_IPaddress.Text.Trim();
string portStr = textBox2_Port.Text.Trim();
int port = Convert.ToInt32(portStr);
int bytesRead = 0;
byte[] buffer = new byte[9];
//------------------------------------------------------------------
IPAddress ipAddress = System.Net.IPAddress.Parse(IPStr);
//create server's tcp listener for incoming connection
try
{
textBox3.Visible = true;
client = new TcpClient();
client.Connect(IPStr, port);
ns = client.GetStream();
while (true)
{
if (ns.DataAvailable)
{
byte[] data = ReadNumberBytes(ns, 9);
ASCIIEncoding encoder = new ASCIIEncoding();
msg = encoder.GetString(data);
textBox3.AppendText(msg);
textBox3.AppendText("\n");
GetData(msg);
}
else
{
Thread.Sleep(4000);
byte[] data = ReadNumberBytes(ns, 9);
ASCIIEncoding encoder = new ASCIIEncoding();
msg = encoder.GetString(data);
GetData(msg);
}
}
client.Close();
}
catch (SocketException se)
{
//message box;
}
}
}
public static byte[] ReadNumberBytes(NetworkStream stream, int n)
{
byte[] buffer = new byte[n];
int bytesRead = 0;
int chunk;
while (bytesRead < n)
{
chunk = stream.Read(buffer, (int)bytesRead, buffer.Length - int)bytesRead);
if (chunk == 0)
{
// error out.
throw new Exception("Unexpected disconnect");
}
bytesRead += chunk;
}
return buffer;
}

Categories