- This topic has 18 replies, 6 voices, and was last updated 11 years, 3 months ago by Anonymous.
-
AuthorPosts
-
March 17, 2013 at 14:41 #491AnonymousInactive
Hello there,
im trying to send a file to a specific host with while maintaining a progress bar and stats about the transer.
I already found StreamSendWrapper and ThreadSafeStream but i dont really get it. Could you provide an example? (btw. im using ProtoSerializer).
Regards
Sp1rit
March 17, 2013 at 18:31 #492MarcFKeymasterHeya Sp1rit,
Thanks for your interest in NetworkComms.Net. Setting up a progress bar is relatively straight forward. You are already on the right track with the StreamSendWrapper, a short example that should get you going is as follows:
On the client side you break the send into multiple instances using ThreadSafeStream and StreamSendWrapper.
//This is our progress percent, between 0 and 1 double progressPercentage = 0; //Initialise stream with 1MB byte[] buffer = new byte[1024*1024]; DPSBase.ThreadSafeStream dataToSend = new DPSBase.ThreadSafeStream(new System.IO.MemoryStream(buffer)); int totalBytesSent = 0; //We will send in chunks of 50KB int sendInChunksOfNBytes = 50 * 1024; //Get the connection to the target Connection connection = TCPConnection.GetConnection(new ConnectionInfo("192.168.0.1", 10000)); do { //Determine the total number of bytes to send //We need to watch out for the end of the buffer when we send less than sendInChunksOfNBytes int bytesToSend = (buffer.Length - totalBytesSent > sendInChunksOfNBytes ? sendInChunksOfNBytes : buffer.Length - totalBytesSent); DPSBase.StreamSendWrapper streamWrapper = new DPSBase.StreamSendWrapper(dataToSend, totalBytesSent, bytesToSend); connection.SendObject("PartitionedSend", streamWrapper); totalBytesSent+=bytesToSend; progressPercentage = ((double)totalBytesSent / buffer.Length); } while (totalBytesSent < buffer.Length);
On the server side you just reassemble the stream as the data comes in:
System.IO.Stream recievedData = new System.IO.MemoryStream(); NetworkComms.AppendGlobalIncomingPacketHandler<byte[]>("PartitionedSend", (packetHeader, connection, incomingBytes) => { Console.WriteLine("\n ... Incoming data from " + connection.ToString()); recievedData.Write(incomingBytes, 0, incomingBytes.Length); });
If you have any issues just post back.
Marc
March 29, 2013 at 18:03 #644AnonymousInactiveThank you now it´s working pretty well. 🙂
Another question:
In library features you write:
Support for sending v.large (>100GB) files.Will the ThreadSafeStream also support larger files in the near future?
Right now it always throws an exception with files over 2GB.March 29, 2013 at 18:58 #645MarcFKeymasterHeya Sp1rit. Great to hear everything works. That exception is known and originates from the limitations of 32bit file systems where you can’t have files larger than 2GB. We had not prioritised fixing it as no one had commented on it, until now. If its something you would like in the near future just let us know.
Regards,
Marc
April 10, 2013 at 22:51 #735AnonymousInactiveJust to update this post. The 2GB limit bug has been fixed for the next release. Within the next week or so.
Regards,
Marc
August 7, 2013 at 02:10 #1018AnonymousInactiveHello,
I work at my school, I have a client-server application in C # with Visual Studio 2010 and I have my first client 1 that connects to server. but now I have a problem to connect a server to another client 2 in a VM (Virtual Machine: Virtual Box Windows 7).Client 2:
* It should be the server connects to the client 2?
* The server sends a message to the client that son located in a virtual machine?
* After sent, the server received a confirmation message from client 2?So it remains to create of client 2 code that receives a message from the server and client 2 sends a confirmation response to server and client 1?
Please find attached client / server code.
Very thank you in advance and regards.thank you
client :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using DPSBase;
using NetworkCommsDotNet;namespace SocketProject.Client
{class Program
{#region [ Fields ]
private static ConnectionInfo connectionInfo = null;
private static Stopwatch _stopWatch = null;
#endregionstatic void Main(string[] args)
{
string serverIP = string.Empty;
int serverPort = 0;
int loopCounter = 1;TCPConnection serverConnection = null;
string result = string.Empty;//Enter Params of the connection
Console.WriteLine(“SVP, saisissez l’adresse IP et le port du serveur (127.0.0.1:10000) : “);
Console.WriteLine();
string serverInfo = Console.ReadLine();serverIP = serverInfo.Split(‘:’).First();
serverPort = int.Parse(serverInfo.Split(‘:’).Last());while (true)
{
NetworkComms.RemoveGlobalIncomingPacketHandler();
connectionInfo = new ConnectionInfo(serverIP, serverPort);
serverConnection = TCPConnection.GetConnection(connectionInfo);//Send Message to the others clients
NetworkComms.AppendGlobalIncomingPacketHandler<string>(“SendMessageToOthersClt”, HandleIncomingCltMessage);
//Send Message to the serveur
NetworkComms.AppendGlobalIncomingPacketHandler<string>(“CustomObjectReply”, HandleIncomingSrvMessage);Console.Write(string.Format(“Entrez votre {0}{1} message : \n “, loopCounter, (loopCounter == 0) ? “er” : “eme”));
string messageToSend = Console.ReadLine();_stopWatch = new Stopwatch();
if (messageToSend.StartsWith(“SendMsg”))
{
int firstSpace = messageToSend.IndexOf(‘ ‘);
serverConnection.SendObject(“SendMessageToOthersClt”, messageToSend.Substring(firstSpace));
}
else
serverConnection.SendObject(“RequestCustomObject”, messageToSend);Console.WriteLine();
if (Console.ReadKey(true).Key == ConsoleKey.Q) break;loopCounter++;
}NetworkComms.Shutdown();
}private static void HandleIncomingSrvMessage(PacketHeader header, Connection connection, string incomingMessage)
{
string messageToShow = string.Empty;
string execTime = string.Empty;messageToShow = “——————————————————————————-\n”;
string[] res = incomingMessage.Trim().Split(‘-’);
if (res.Length > 1)
execTime = ((_stopWatch.Elapsed.Milliseconds * 1000) + int.Parse(res[0])).ToString();
else
execTime = (_stopWatch.Elapsed.Milliseconds * 1000).ToString();switch (res[1])
{
case “LaunchVM”:
messageToShow += “Virtual Box Lancée après ” + execTime + “(ns)\n”;
break;
case “LaunchVagrant”:
messageToShow += “Vagrant Lancée après ” + execTime + “(ns)\n”;
break;
case “SendMsg”:
messageToShow += “Le message envoyée aprés ” + execTime + “(ns)\n”;
break;
default:
messageToShow += “Le message ‘” + res[1] + “‘ a été reçu par le serveur après ” + execTime + “(ns)\n”;
break;
}
messageToShow += “——————————————————————————-\n”;
Console.Write(messageToShow);
}private static void HandleIncomingCltMessage(PacketHeader header, Connection connection, string incomingMessage)
{
TimeSpan ts = _stopWatch.Elapsed;
Console.Write(string.Format(“Message reçu de la part d’un autre client : {0} \n “, incomingMessage));
}
}}
server:
using System;
using NetworkCommsDotNet;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DPSBase;
using System.Threading;namespace SocketProject.Server
{
class Program
{
static void Main(string[] args)
{
NetworkComms.AppendGlobalIncomingPacketHandler<string>(“RequestCustomObject”, (packetHeader, connection, message) =>
{
Stopwatch stopWatchLaunchVagrant = new Stopwatch();
stopWatchLaunchVagrant.Start();string msgConsole = string.Empty;
string elapsedTime = “”;string process = “”;
string workingDirectory = “”;
string arg = “”;msgConsole += “—————————————————————————–\n”;
msgConsole += string.Format(“Message reçu de la part Client {0}, le contenu est : {1} \n”, “[” + connection.ConnectionInfo.NetworkIdentifier.Value + ” ” + connection.ConnectionInfo.LocalEndPoint.Address.ToString() + “:” + connection.ConnectionInfo.LocalEndPoint.Port.ToString() + “]“, message);if (message == “LaunchVM”)
{
process = @”VirtualBox.exe”;
workingDirectory = @”C:\Program Files\Oracle\VirtualBox\”;
}
else if (message == “LaunchVagrant”)
{
process = “cmd.exe”;
workingDirectory = @”C:\Vagrant\”;
arg = “vagrant up”;
}
else if (message == “LaunchVagrantDistant”)
{
process = “cmd.exe”;
workingDirectory = @”\\dauphine-PC\Vagrant\”;
arg = “vagrant up”;
}
else if (message == “test”)
{
process = “devenv.exe”;
workingDirectory = @”C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\”;
}ProcessStartInfo psi = new ProcessStartInfo(process)
{
UseShellExecute = true,
RedirectStandardOutput = false,
RedirectStandardInput = false,
RedirectStandardError = false,
CreateNoWindow = true,
WorkingDirectory = workingDirectory
};
if (!(string.IsNullOrEmpty(arg)))
psi.Arguments = “/C ” + arg;
//Process.Start(psi);
System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi);stopWatchLaunchVagrant.Stop();
elapsedTime = (p.TotalProcessorTime.TotalMilliseconds * 1000 + stopWatchLaunchVagrant.ElapsedMilliseconds * 1000).ToString();msgConsole += “Temps d’exécution est : ” + elapsedTime + “\n”;
msgConsole += “—————————————————————————–\n”;Console.Write(msgConsole);
connection.SendObject(“CustomObjectReply”, elapsedTime + “-” + message);
});NetworkComms.AppendGlobalIncomingPacketHandler<string>(“SendMessageToOthersClt”, (packetHeader, connection, message) =>
{
string msgConsole = string.Empty;
msgConsole += “—————————————————————————–\n”;
msgConsole += string.Format(“Le Client {0} a envoyé ce message : \” {1} \” aux autres clients \n”, “[” + connection.ConnectionInfo.NetworkIdentifier.Value + ” ” + connection.ConnectionInfo.LocalEndPoint.Address.ToString() + “:” + connection.ConnectionInfo.LocalEndPoint.Port.ToString() + “]“, message);
var allRelayConnections = (from current in NetworkComms.GetExistingConnection() where current != connection select current).ToArray();
foreach (var relayConnection in allRelayConnections)
{
try
{
relayConnection.SendObject(“SendMessageToOthersClt”, message);
}
catch (CommsException) { /* Catch the comms exception, ignore and continue */ }
}
msgConsole += “—————————————————————————–\n”;
Console.Write(msgConsole);
});NetworkComms.AppendGlobalConnectionEstablishHandler((connection) => { Console.Write(string.Format(” Nouveau client connecté : [IP : {0}, PORT : {1}] \n”, connection.ConnectionInfo.LocalEndPoint.Address.ToString(), connection.ConnectionInfo.LocalEndPoint.Port.ToString())); });
TCPConnection.StartListening(true);
foreach (System.Net.IPEndPoint localEndPoint in TCPConnection.ExistingLocalListenEndPoints())
Console.WriteLine(“Serveur demarré – Infos : {0}:{1}”, localEndPoint.Address, localEndPoint.Port);
Console.WriteLine(“\n Cliquez sur une touche pour fermer le serveur.”);
Console.ReadKey(true);
NetworkComms.Shutdown();
}public static string elapsedTime { get; set; }
}
}August 7, 2013 at 10:06 #1019AnonymousInactive@Hajaji – What are the IP addresses of your server and client?
August 7, 2013 at 10:41 #1020AnonymousInactiveheloo MarcF,
I work on my computer and I use address 127.0.0.1 and port number 10000 (127.0.0.1:10000) is to connect the client1 to server. and there is just to connect to another server client 2?
I thank you in advance for your efforts and Very Best Regards
August 7, 2013 at 10:52 #1021AnonymousInactive127.0.0.1 is a local only address, you cannot use this address to connect across machines. You should be looking for IP addresses in the private ranges which are typically 192.168.x.x or 10.x.x.x.
Marc
August 7, 2013 at 11:23 #1022AnonymousInactiveWelcome back MarcF,
so when I do the execution console server on my physical machine displays the following address: @ IP: 193.51.91.5:10000 & @ IP: 127.0.0.1:10000
and when I do the execution of the console server in the virtual machine (virtual box with windows 7) displays the following address: @ IP: 192.51.91.5:10000 & @ IP: 127.0.0.1:10000
thank you very much for your effort. -
AuthorPosts
- You must be logged in to reply to this topic.