Reputation: 4373
I want to send and receive some data from my server, but I don't know how to do this...
Basically I want to: Send: "some string" To: IP: 10.100.200.1 Port: 30000
Receive/read the response
Can someone give me some basic example or point me to a simple (working) tutorial?
Upvotes: 0
Views: 836
Reputation: 712
Simple synchronous TcpClient sending a text string and receiving a text string.
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
public class SimpleTcpClient {
public static void Main() {
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect("10.100.200.1",30000);
String textToSend = "HelloWorld!";
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] data = asen.GetBytes(textToSend);
stm.Write(data,0,data.Length);
//You might want to wait a bit for an answer (Thread.Sleep or simething)
byte[] responseData = new byte[1024];
string textRecevided = "";
int read = 0;
do {
read = stm.Read(responseData, 0, responseData.Length);
for (int i=0; i < read; i++)
{
textRecevided += (char)responseData[i];
}
} while (read > 0);
Console.Write(textRecevied);
tcpclnt.Close();
}
}
Upvotes: 1
Reputation: 101150
Your question is a bit broad and it could easily be answered by googling.
The thing that you are looking for is called a Socket
. But in your case I would use a TcpClient
since it makes the handling a bit easier.
Google "TcpClient
c#" and you'll find some nice examples. Then come back with more specific questions if you can't get stuff working.
Upvotes: 0