I want to send two different lines of XML to a socket as follows:
<GetServerTime UpTimeAtRequest="1919"/>
<Subscribe FrontId="priceFeed" URI="ffo:/price/productCode=VP-4-6-"/>
I'm using Hercules to test this, but it won't let me send it in that format. How should I delimit or format the XML above so I can send it directly to the socket with Hercules after connecting to the appropriate ip address and port?
I would be happy to send this using a WebClient or something in C# also.
Thanks.
I've no idea what Hercules is, but sending arbitrary data over a client is easy:
using (var client = new TcpClient())
{
client.Connect(host, porg);
using (var stream = client.GetStream())
{
// Or some other encoding, of course...
byte[] data = Encoding.UTF8.GetBytes(xmlString);
stream.Write(data, 0, data.Length);
// Whatever else you want to do...
}
}
WebClient is pretty simple to use (assuming your socket is using the HTTP protocol), so using UploadString would look something like this:
Uri uri = new Uri(#"http://www.mywebsite.com/someurl");
string myXml = "<insert valid xml here> /"
using (WebClient wc = new WebClient()
{
wc.UploadString(uri, myXml);
}
I'd only worry that your xml isn't valid as it has two root nodes and no xml header.
Related
I'm trying to send a zip file from a server to client using TCP ports.
I'm creating a zip file in a server folder, reading it into a byte array, sending it to a connected client, writing the bytes into a file and storing it in a client folder. Currently the process is just on the same computer.
However, whenever the zip file is saved into the client folder, it's either an invalid zip or a zip with corrupted files. When this happens they'll have the exact same size as the zip file in the server folder, so I don't think I'm losing any bytes in the network transfer. The server zip file also works as expected, you are able to open and view contents in the folder.
The hashes between the client zip and the server zip are different. I've tested with regular .txt, .cs and .csv files, and those are sent and can be opened in the client folder. They have the same has as their server counterpart.
The zip file I'm sending just has a .csv, a .txt, and a .cs file in it.
This is my code
Server:
using System.Net.Sockets;
using System.Net;
using System.Security.Cryptography;
using System.IO.Compression;
String filename = "C:\\BabyServerZip\\ServerFiles.zip";
File.Delete("C:\\BabyServerZip\\ServerFiles.zip");
ZipFile.CreateFromDirectory("C:\\BabyServerSend", "C:\\BabyServerZip\\ServerFiles.zip");
IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint endpoint = new(ipAddress, 58008);
Socket listener = new(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(endpoint);
listener.Listen();
var handler = await listener.AcceptAsync();
var buffer = new byte[1024];
buffer = File.ReadAllBytes(filename);
handler.Send(buffer);
Client:
using System.Text;
using System.Net;
using System.Net.Sockets;
String outputPath = "C:\\BabyClientReceive\\sent.zip";
IPHostEntry = ipHostInfo = Dns.GetHostEntry("localhost");
IPAddress serverIP = ipHostInfo.AddressList[0];
IPEndPoint clientEnd = new(serverIP, 58008);
Socket clientSocket = new(clientEnd.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
clientSocket.ConnectAsync(clientEnd);
while (true)
{
if (clientSocket.Available > 0)
{
using (StreamWriter fw = new StreamWriter(outputPath))
{
char[] response;
do
{
var buffer = new byte[1024];
int received = clientSocket.Receive(buffer, SocketFlags.None);
response = Encoding.ASCII.GetChars(buffer, 0, received);
fw.Write(response, 0, received);
while (response.Length == 1024);
fw.Flush();
fw.Close();
}
}
}
Is there something that I'm missing in order to correctly send zip files over a network? Why are the uncompressed files working correctly and the zip files breaking?
Fixed the issue thanks to the tip from #MySkullCaveIsADarkPlace.
StreamWriter is a text writer, and zip files are binary. Switching the StreamWriter for BinaryWriter fixed the problem.
Your client code is all wrong. You are using a StreamWriter as if the Zip is text, but it's not, it's binary. Replacing it with a BinaryWriter is silly also, because that is primarily for writing custom binary formats bit by bit.
There are numerous other issues with the way you are handling this, as you need to expect that the response will not come as a single blob.
Instead you should not use raw sockets, but use TcpClient. You just need to copy the stream straight into a FileStream.
There are also missing await and you should use IPAddress.Any instead of localhost.
String outputPath = "C:\\BabyClientReceive\\sent.zip";
using TcpClient client = new();
await clientSocket.ConnectAsync(IPAddress.Any, 58008);
using (var ns = client.GetStream())
using (var fs = new FileStream(outputPath, FileMode.Create, FileAccess.Write))
{
await ns.CopyToAsync(fs);
}
I have a simple client and server in C#. The goal is for the client to send an XML document to the server, and then the server should respond with a different XML document. The server is blocking when I try to receive the input/request XML with XmlDocument.Load(NetworkStream).
Server:
TcpListener t = new TcpListener(IPAddress.Any, 4444);
t.Start();
TcpClient c = t.AcceptTcpClient();
NetworkStream s = c.GetStream();
XmlDocument req = new XmlDocument();
req.Load(s);
string respString = "<response><data>17</data></response>";
XmlDocument resp = new XmlDocument();
resp.LoadXml(respString);
resp.Save(s);
Client:
TcpClient t = new TcpClient("localhost", 4444);
NetworkStream s = t.GetStream();
string reqStr = "<request><parameters><param>7</param><param>15</param></parameters></request>";
XmlDocument req = new XmlDocument();
req.LoadXml(reqStr);
req.Save(s);
XmlDocument resp = new XmlDocument();
resp.Load(s);
Console.WriteLine(resp.OuterXml);
I tried adding a Flush() in the client after it saves the request XmlDocument to the stream, but that didn't seem to help. Originally I tried having the server read all of the input from the client to a MemoryStream, but then I found that there was no way to signify to the server that all the input was done without disconnecting, which meant that then the client couldn't read its input.
I can send XML input to the server from a file with netcat and everything works fine. This works whether I use XmlDocument.Load(NetworkStream) in the server, or read all the input into a MemoryStream. What is it that netcat is doing in this case that I am not doing in my C# client, and how do I do it in C#? Should I be going about this differently?
Tcp connection is bidirectional, and you can close one half of it while still having the other half open. In this case, you can close client to server half after sending all data, and then you can receive response over server to client half still. You can do it for your example like this:
TcpClient t = new TcpClient("localhost", 4444);
NetworkStream s = t.GetStream();
string reqStr = "<request><parameters><param>7</param><param>15</param></parameters></request>";
XmlDocument req = new XmlDocument();
req.LoadXml(reqStr);
req.Save(s);
// important line here! shutdown "send" half of the socket connection.
t.Client.Shutdown(SocketShutdown.Send);
XmlDocument resp = new XmlDocument();
resp.Load(s);
Console.WriteLine(resp.OuterXml);
Don't forget dispose network stream on a server's side after you sent all data:
TcpListener t = new TcpListener(IPAddress.Loopback, 4444);
t.Start();
TcpClient c = t.AcceptTcpClient();
using (NetworkStream s = c.GetStream()) {
XmlDocument req = new XmlDocument();
req.Load(s);
Console.WriteLine("Got request: {0}", req.OuterXml);
string respString = "<response><data>17</data></response>";
XmlDocument resp = new XmlDocument();
resp.LoadXml(respString);
resp.Save(s);
}
Actually if whole communication is single request followed by single response - you can use this technique instead of custom protocols over tcp (remember to use timeouts and properly dispose your streams and tcp clients).
Otherwise, remember that network stream is kind of open connection between client and server - it does not have explicit "end". When you are doing XmlDocument.Load - it will read until it is possible (that is until Read returns with 0 bytes read), so it blocks in your case. You should define your own protocol over tcp, so that you yourself can define the message boundary. Simple way would be - first 4 bytes define the length of the following message. So you read first 4 bytes and then read until that length is reached or timeout occurs.
I have HTTP server written using HttpListener and want zero-copy technology for sending files to clients.
Is there are any option to use TransmitFile to respond?
I assume you're referring to HttpResponse.TransmitFile? HttpListener doesn't buffer the response content, so you just need to write directly to the output stream.
You can use an extension method like this to mimic the ASP.NET behavior:
public static void TransmitFile(this HttpListenerResponse response, string fileName)
{
using (var fileStream = File.OpenRead(filename))
{
response.ContentLength64 = fileStream.Length;
fileStream.CopyTo(response.OutputStream);
}
}
I'm relatively new to C# but here goes:
I am developing a remote file service client/server console application in C# which is supposed to exchange messages using synchronous sockets.
One of the main problems (even thought it might seem simple) is to return a string from the server, to the client using streamreader/streamwriter.
The application user a command line interface with options (from a switch statement) to execute actions. I.e. typing 1 and enter would execute the code to send the string from the server to the client.
Below is a sample code from the client:
try
{
using (TcpClient client = (TcpClient)clientObject)
using (NetworkStream stream = client.GetStream())
using (StreamReader rd = new StreamReader(stream))
using (StreamWriter wr = new StreamWriter(stream))
{
string menuOption = rd.ReadLine();
switch (menuOption)
{
case "1":
case "one":
string passToClient = "Test Message!";
wr.WriteLine(passToClient);
break;
}
while (menuOption != "4");
}
}
I understand the code I posted is just a snippet of the program, but it would take up a fair amount of space and was hoping you can gather what I mean from this, if not I will post more.
This is just to give a general idea of what I am going for,
I appreciate any help / advice you can give. Its not so much code examples I'm looking for (although a little would help) but more some explanation on streamreader/writer as I cant seem to understand much of what is online.
Thanks.
I think you're just missing a wr.flush(); but this article should cover everything you need:
http://thuruinhttp.wordpress.com/2012/01/07/simple-clientserver-in-c/
Whenever you use StreamWriter you need to Flush() the contents of the stream. I'll quote MSDN as the reason becomes quite clear:
Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.
You can call it quite simply like:
wr.flush();
Solution can be simpler:
StreamWriter wr = new StreamWriter(stream) { AutoFlush = true }
I just ran a test using your code, and it works fine, I can step right into the "one" case statement.
I am guessing you are either not including the line-break in the string you are sending, or you just have the TcpClient or TcpListener configured wrong.
Here is the Client-Side code for my test:
TcpClient client = new TcpClient("127.0.0.1", 13579);
string message = "one" + Environment.NewLine;
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
NetworkStream stream = client.GetStream();
stream.Write(data, 0, data.Length);
Here is the Server-Side:
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
TcpListener server = new TcpListener(localAddr, 13579);
server.Start();
TcpClient client = server.AcceptTcpClient();
using (client)
using (NetworkStream stream = client.GetStream())
using (StreamReader rd = new StreamReader(stream))
using (StreamWriter wr = new StreamWriter(stream))
{
string menuOption = rd.ReadLine();
switch (menuOption)
{
case "1":
case "one":
string passToClient = "Test Message!";
wr.WriteLine(passToClient);
break;
}
while (menuOption != "4") ;
}
Just run the server-side code first, which will block while waiting for connection and then while waiting for data. Then run the client-side code. You should be able to catch a breakpoint on the switch().
With my code I can read a message on the server and write from the client. But I am not being able to write a response from the server and read in the client.
The code on the client
var cli = new TcpClient();
cli.Connect("127.0.0.1", 6800);
string data = String.Empty;
using (var ns = cli.GetStream())
{
using (var sw = new StreamWriter(ns))
{
sw.Write("Hello");
sw.Flush();
//using (var sr = new StreamReader(ns))
//{
// data = sr.ReadToEnd();
//}
}
}
cli.Close();
The code on the server
tcpListener = new TcpListener(IPAddress.Any, port);
tcpListener.Start();
while (run)
{
var client = tcpListener.AcceptTcpClient();
string data = String.Empty;
using (var ns = client.GetStream())
{
using (var sr = new StreamReader(ns))
{
data = sr.ReadToEnd();
//using (var sw = new StreamWriter(ns))
//{
// sw.WriteLine("Hi");
// sw.Flush();
//}
}
}
client.Close();
}
How can I make the server reply after reading the data and make the client read this data?
Since you are using
TcpClient client = tcpListener.AcceptTcpClient();
, you can write back to the client directly without needing it to self-identify. The code you have will actually work if you use Stream.Read() or .ReadLine() instead of .ReadToEnd(). ReadToEnd() will block forever on a network stream, until the stream is closed. See this answer to a similar question, or from MSDN,
ReadToEnd assumes that the stream
knows when it has reached an end. For
interactive protocols in which the
server sends data only when you ask
for it and does not close the
connection, ReadToEnd might block
indefinitely because it does not reach
an end, and should be avoided.
If you use ReadLine() at one side, you will need to use WriteLine() - not Write() - at the other side. The alternative is to use a loop that calls Stream.Read() until there is nothing left to read. You can see a full example of this for the server side in the AcceptTcpClient() documentation on MSDN. The corresponding client example is in the TcpClient documentation.
Cheesy, inneficient, but does the trick on a one-time throwaway program:
Client: In the stream, include the port and IP address it wishes to receive the response from.
Client: Create a listener for that
port and IP.
Server: Read in the port/IP info and
in turn connect, then send the reply
stream.
However, this is a great place to start, look into Sockets class for proper bi-directional communication.