I'll try and explain my question below, I have tried googling for an answer but firstly, I don't really know what I should be googling and I haven't found anything that makes sense to me, I was wondering if someone could explain it? Many Thanks.
Hello. I am trying to send a simple network packet using TCP, I have done it using UDP pretty easily as its really easy with UDP, I was wondering if anyone could help me do the equivalent in TCP? I tried using a TcpClient, but it doesn't have a Send method the same as UDP?
public void OnUdp()
{
var client = new UdpClient(Host, Port);
client.Send(rubbish, rubbish.Length);
}
This is the example from https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx
static void Connect(String server, String message)
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
Int32 port = 13000;
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("\n Press Enter to continue...");
Console.Read();
}
Related
I'm trying to use tcpclient to retrieve data from a tcp server, sending a request and receiving a response, it works fine except for one thing.
When I try to use multiple times networkstream.readasync and then networkstream.writeasync the readasync function reads the previous response of the previous writeasync and not of the last one.To fix that I have to set a timeout before reading. Instead of setting a timeout is there any way to wait until the new data are available?
Pseudocode Example:
connectasync(host,port);
//reads a hello message from the server
networkstram.readasync();
//sending a request to the server
networkstram.writeasync();
//reads again the hello message from the previous read
//not the response from the previously sended writeasync
networkstram.readasync()
Pseudocode Solution:
connectasync(host,port);
//reads a hello message from the server
networkstram.readasync();
//sending a request to the server
networkstram.writeasync();
//wait for 1 second
wait(1000)
//reads correctly
networkstram.readasync()
If you have any better way to wait the newly available data instead of using a fixed timeout let me know.
Thank you.
UPDATE
NOTE:I even tried with the synchronous version of read and write still the same.
Am Just using async to no block the user interface.
public async Task<string> sendQuery()
{
try
{
client.Connect(ConfigParameters.ip, ConfigParameters.port);
if (client.Connected == true)
{
Console.WriteLine("Connected");
var networkStream = client.GetStream();
// Receive data from server
//Receiving HELLO message from the server
byte[] buffer = new byte[1024];
await networkStream.ReadAsync(buffer, 0, buffer.Length);
var serverResponse = Encoding.ASCII.GetString(buffer);
Console.WriteLine("Server: " + serverResponse);
Array.Clear(buffer,0,buffer.Lenght);
Array.Resize(ref buffer, 1024);
// Send data to server
// send query to the server
string data = QueryStore.queryStart+QueryStore.query1.getLRC() + QueryStore.queryEnd;
buffer = System.Text.Encoding.ASCII.GetBytes(data);
await networkStream.WriteAsync(buffer, 0, buffer.Length);
Array.Clear(buffer,0,buffer.Lenght);
Array.Resize(ref buffer, 1024);
// Receive data from server
// receive still HELLO message
buffer = new byte[1024];
await networkStream.ReadAsync(buffer, 0, buffer.Length);
serverResponse = Encoding.ASCII.GetString(buffer);
Console.WriteLine("Server: " + serverResponse);
networkStream.Close();
client.Close();
return "ok";
}
}
catch(SocketException)
{
client.Close();
return "error";
}
finally
{
client.Close();
return "";
}
}
C# I am developing a MIP plugin for Milestone VMS.
I have a problem while connecting to SocketIO with C#.
I have tried to connect to SocketIO with TcpClient, Socket, ClientWebSocket
TcpClient tcpClient = new TcpClient();
tcpClient.Connect("127.0.0.1, 3001);
I also have tried to connect with ClientWebSocket but again no reaction in server side.
using (var client = new ClientWebSocket())
{
// await client.ConnectAsync(new Uri("ws://192.168.100.25:8090/?token="),timeout.Token);
await client.ConnectAsync(new Uri(LOCAL_PATH), timeout.Token);
var buffer = new ArraySegment<byte>(new byte[1000]);
var result = await client.ReceiveAsync(buffer, timeout.Token);
}
Can anyone provide some libraries that may serve as clients to SocketIO?
URI has this syntax: http://127.0.0.1:3001?token=xxx
here is a tested code that i use , supposing your server is running , you need to pass the IP or HostName and port number , then come the payload or message that you want to send :
private bool ConnectAndSendMessage(String server, Int32 port, String message)
{
try
{
// Create a TcpClient.
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
// Buffer to store the response bytes receiver from the running server.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
// Close everything.
stream.Close();
client.Close(); return true;
}
catch (ArgumentNullException e)
{
_txtStyling.WriteCustomLine(string.Format("ArgumentNullException: {0} \n\n", e.Message), 14, false, false, Brushes.Red); return false;
}
catch (SocketException e)
{
_txtStyling.WriteCustomLine(string.Format("SocketException: {0} \n\n", e.Message), 14, false, false, Brushes.Red); return false;
}
}
Currently developing a simple message server using sockets and sometimes the TCPClient receives the correct number of bytes but each byte is 0.
Here's the sender code.
try
{
//c.clientSocket.NoDelay = true;
// Send back an OK
var clientStream = c.clientSocket.GetStream();
var Response = JsonConvert.SerializeObject(new Packet("SERVER", c.ClientName, new List<Payload>() { new Payload(MessageLibrary.Commands.OK, null) }));
var msg = System.Text.Encoding.ASCII.GetBytes(Response);
clientStream.Write(msg, 0, msg.Length);
}
catch (Exception ex)
{
if (ExceptionRaised != null)
ExceptionRaised(c.ClientName, ex);
}
Response = "{\"TimeStamp\":\"2016-03-18T08:15:15.0881326+00:00\",\"Sender\":\"SERVER\",\"Payload\":[{\"Command\":\"OK\",\"CommandValue\":\"\"}],\"Destination\":\"GBCO0101\"}"
Msg contains 139 bytes
So this seems ok, here is the receiving code.
static void OnDataRecieved(IAsyncResult result)
{
TcpClient client = result.AsyncState as TcpClient;
// Get a stream object for reading and writing
try
{
NetworkStream stream = client.GetStream();
int ReadBytes = stream.EndRead(result);
if (ReadBytes == 0)
{
// Client gone
Console.WriteLine("Server lost");
}
else
{
// Translate data bytes to a ASCII string.
var data = System.Text.Encoding.ASCII.GetString(ClientReadBuffer, 0, ReadBytes);
ClientReadBuffer = new byte[ClientReadBuffer.Length];
stream.BeginRead(ClientReadBuffer, 0, ClientReadBuffer.Length, new AsyncCallback(OnDataRecieved), client);
ProcessData(data);
}
}
catch (Exception ex)
{
Console.WriteLine("lost connection");
Console.WriteLine(ex.Message);
}
}
If I take a look at ProcessData(data); I can see that data = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
ReadBytes = 139
So the right amount of bytes seems to be correct but the data itself is wrong. What can cause this?
It's unlikely.
Are you really using ClientReadBuffer on the first stream.BeginRead() (it's not included in the code above)? You probably have one somewhere that doesn't do the read in the same way.
And why do you create a new instance of it for every read? Waste of resources. Just reuse it.
Another thing is that TCP is stream based. Don't expect the bytes received to match the buffer that you sent. See this question for instance.
My IP-Camera is configured to send alarm messages to my computer.
IPAddress of camera: 10.251.51.1
IPAddress of my computer: 10.251.51.136
The camera can be configured to send messages to any port on my computer.
So, I set the alarm destination to my computer's IP Address: 10.251.51.136 at port 3487.
Now, what should be done at my computer to get the message sent by the camera ?
I tried to write a TCPListener from MSDN and the code is below:
Int32 port = 3487;
IPAddress localAddr = IPAddress.Parse("10.251.51.136");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
server.Start();
// Start listening for client requests.
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
server.Start();
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
But this does not seem to be working.
Or is my entire approach flawed ? Should i implement TCPListener or TCPServer instead for my scenario above?
Any pointers why?
I'm a Java Developer Trying to build a Simple C# TCP Client. however for the life of me I can't figure out how to get this bloody thing to work. Here is my TCPClient code. BTW, I stole this directly from msdn. http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx
public static void Connect(String server, int port, String message)
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
Console.WriteLine("Sent: {0}", message);
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("\n Press Enter to continue...");
Console.Read();
}
Here is my Java Server.
private ServerSocket socket;
private JAXBContext jaxbContext;
boolean listening = true;
#SuppressWarnings("unused")
private HMSAgentService() {
}
public HMSAgentService(int port) {
try {
this.socket = new ServerSocket(port);
logger.debug("Agent Service listening on port : " + port);
this.jaxbContext = HMSAgentUtil.getJAXBContext();
while (listening) {
new AgentServiceThread(socket.accept(), jaxbContext).start();
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
} catch (JAXBException e) {
logger.error(e.getMessage(), e);
}
}
It simply starts off a new thread when it receives a client connection.
Now my problem is that The program never moves past the stream.Write(). Also the server never receives the message. Only after I call Stream.close() does the server receive the message. But that essentially closes the connection and the client can't receive any more messages. Why is happening. I've tried using Sockets, StreamWriters, StreamReaders and its the same story.
At this point i'm contemplating using The Asynchronous method, but I'm trying to keep the program as simple as possible, since there is no need for it. Is there anyway of signaling the end of a Write?