C# TCP/IP send raw string to remote IP/port and get response synchronize mode
public static string TcpSend(string IP, int port, string data)
{
string ret = null;
try
{
TcpClient client = new TcpClient();
if (!client.ConnectAsync(IP, port).Wait(2000)) return null;
client.SendTimeout = 1000;
Stream stream = client.GetStream();
stream.ReadTimeout = 6000;
Byte[] bytes = System.Text.Encoding.ASCII.GetBytes(data);
stream.Write(bytes, 0, bytes.Length);
if (client.ReceiveBufferSize > 0)
{
bytes = new byte[client.ReceiveBufferSize];
int r = stream.Read(bytes, 0, client.ReceiveBufferSize);
ret = Encoding.ASCII.GetString(bytes, 0, r);
}
stream.Close();
client.Close();
}
catch (Exception)
{
return null;
}
return ret;
}