Service side:
Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
Using System.Threading.Tasks;
Namespace Ceshi1
{
Class Program
{
static void Main (string[] args)
{
String sendstring = null;//the string to send
byte[] SendData = null;//byte array to send
TcpClient client = Null;//tcpclient instance
NetworkStream stream = null;//network stream
IPAddress Remoteip = Ipaddress.parse ("127.0.0.1");//Remote host IP
int remoteport = 11000;//remote host port
while (true)//Dead loop
{
sendstring = Console.ReadLine ();//Gets the string to send
SendData = Encoding.Default.GetBytes (sendstring);//Gets the byte array to send
Client = new TcpClient ();//instantiation of TcpClient
Try
{
Client. Connect (REMOTEIP, remoteport);//Connect remote host
}
catch (System.Exception ex)
{
Console.WriteLine ("The connection timed out, the server is not responding!") ");//Connection Failed
Console.readkey ();
Return
}
stream = client. GetStream ();//Get network stream
Stream. Write (senddata, 0, senddata.length);//write data to a network stream
Stream. Close ();//Shut Down network stream
Client. Close ();//Shutdown client
}
}
}
}
Client receiving end:
Using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
Namespace Ceshi
{
Class Program
{
static void Main (string[] args)
{
TcpClient client = null;
NetworkStream stream = null;
byte[] buffer = NULL;
string receivestring = null;
IPAddress Localip = Ipaddress.parse ("127.0.0.1");
int localport = 11000;
TcpListener listener = new TcpListener (Localip, LocalPort);//instantiate with local IP and Port listener
Listener. Start ();//Begin Monitoring
while (true)
{
Client = listener. AcceptTcpClient ();//Accept a client
Buffer = new Byte[client. Receivebuffersize];
stream = client. GetStream ();//Get network stream
Stream. Read (buffer, 0, buffer. LENGTH);//Read the data in the network stream
Stream. Close ();//Closed stream
Client. Close ();//Shutdown client
receivestring = Encoding.Default.GetString (buffer). Trim (' n ');//Convert to String
Console.WriteLine (receivestring);
}
}
}
}
C#TCP, network communication example