作为客户端,C# TCP通信协议,客户端主动连接服务器
private void button9_Click(object sender, EventArgs e)
{
//TCP连接第三步:客户端请求连接
TcpClient tclient = new TcpClient();
tclient.Connect("192.168.1.103",9000);//服务器IP与端口,连接服务器
//TCP连接第四步:服务器应答
//tclient.Client.Send(Encoding.UTF8.GetBytes(DTU_RealData()));
textBox1.Text = DTU_RealData();//显示发送的内容
tclient.Client.Send(Encoding.Default.GetBytes(DTU_RealData())); //此种方法能显示中文
byte[] data=new byte[500];
if (tclient.Available > 0)
{
try
{
int length = tclient.Client.Receive(data);//会卡死,等待数据
textBox2.Text = Encoding.Default.GetString(data, 0, length);//显示接受的内容
}
catch (Exception ex)
{
textBox2.Text = ex.ToString();
}
}
}
作为服务器,C#
private void button10_Click(object sender, EventArgs e)
{
string _ip = GetIpAddress();
//TCP连接第二步:服务器建立监听
IPAddress ipa = IPAddress.Parse(_ip);
TcpListener myListener = new TcpListener(ipa,8080);
myListener.Start();//
TcpClient tcpClient = myListener.AcceptTcpClient();//等待状态
NetworkStream ns = tcpClient.GetStream();
byte[] _data = new byte[100];
ns.Read(_data, 0, 100);
byte[] _Rdata=Encoding.UTF8.GetBytes(textBox1.Text);//
ns.Write(_Rdata, 0, _Rdata.Length);
ns.Close();
myListener.Stop();
}