I would like to send data over internet through a desktop application. I know a little bit about sockets. I have transferred the data within the LAN, but now I want to transfer the data over the internet. What is the best way to transfer both large and small quantities of data?
My system is connected to the server which has the access to the internet. My system's IP address is dynamic. I don't know how to send the data to another system which is connected to the internet. Do I need to find the router address? (My IP address is generated as 192.168.1.15).
Is using a socket enough, or is HTTP required?
If all you want to do is transfer raw data from one machine to another it's very easy to do using a TCP socket.
Here's a quick example.
Server:
ThreadPool.QueueUserWorkItem(StartTCPServer);
private static void StartTCPServer(object state) {
TcpListener tcpServer = new TcpListener(IPAddress.Parse("192.168.1.15"), 5442);
tcpServer.Start();
TcpClient client = tcpServer.AcceptTcpClient();
Console.WriteLine("Client connection accepted from " + client.Client.RemoteEndPoint + ".");
StreamWriter sw = new StreamWriter("destination.txt");
byte[] buffer = new byte[1500];
int bytesRead = 1;
while (bytesRead > 0) {
bytesRead = client.GetStream().Read(buffer, 0, 1500);
if (bytesRead == 0) {
break;
}
sw.BaseStream.Write(buffer, 0, bytesRead);
Console.WriteLine(bytesRead + " written.");
}
sw.Close();
}
Client:
StreamReader sr = new StreamReader("source.txt");
TcpClient tcpClient = new TcpClient();
tcpClient.Connect(new IPEndPoint(IPAddress.Parse("192.168.1.15"), 5442));
byte[] buffer = new byte[1500];
long bytesSent = 0;
while (bytesSent < sr.BaseStream.Length) {
int bytesRead = sr.BaseStream.Read(buffer, 0, 1500);
tcpClient.GetStream().Write(buffer, 0, bytesRead);
Console.WriteLine(bytesRead + " bytes sent.");
bytesSent += bytesRead;
}
tcpClient.Close();
Console.WriteLine("finished");
Console.ReadLine();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With