服务器端代码
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- namespace TCP通信
- {
- class Program
- {
- static void Main(string[] args)
- {
- try
- {
- //把ip地址转换为实例
- IPAddress ipa = IPAddress.Parse("127.0.0.1");
- //监听端口8001
- TcpListener mylsn = new TcpListener(ipa, 8001);
- //开启监听
- mylsn.Start();
- //输出监听成功的信息
- Console.WriteLine("在8001启动服务,等待连接");
- //等待处理接入连接请求
- while (true)
- {
- Socket mysock = mylsn.AcceptSocket();
- Console.WriteLine("有连接,连接来自" + mysock.RemoteEndPoint);
- work w = new work();
- w.mysock = mysock;
- w.mylsn = mylsn;
- Thread t = new Thread(new ThreadStart(w.main));
- t.Start();
- }
- }
- catch
- { }
- finally
- { }
- }
- }
- public class work
- {
- public Socket mysock;
- public TcpListener mylsn;
- public void main()
- {
- //接收客户端消息
- byte[] data = new byte[100];
- mysock.Receive(data);
- string rt = System.Text.UTF8Encoding.UTF8.GetString(data);
- Console.WriteLine(rt);
- //给客户端发消息
- mysock.Send(UTF8Encoding.UTF8.GetBytes("回发给客户端"));
- //释放资源
- mysock.Close();
- mylsn.Stop();
- }
- }
- }
客户端代码
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
- namespace TCP通信客户端
- {
- public class Class1
- {
- public static void Main()
- {
- //新建客户端套接字
- TcpClient tclient = new TcpClient();
- //连接服务器
- tclient.Connect("127.0.0.1", 8001);
- Console.WriteLine("输入要发送的消息");
- //读入要传输的字符
- string str = Console.ReadLine();
- //得到流
- Stream stm = tclient.GetStream();
- //发送字符串
- ASCIIEncoding asen = new ASCIIEncoding();
- byte[] data = asen.GetBytes(str);
- stm.Write(data, 0, data.Length);
- //接受服务器返回的消息
- byte[] back = new byte[100];
- int k = stm.Read(back, 0, 100);
- //输出服务器返回的消息
- for (int i = 0; i < k; i++)
- {
- Console.Write(Convert.ToChar(back[i]));
- }
- //关闭连接
- tclient.Close();
- }
- }
- }
根据TCP/IP设计者的设计初衷,当mysock.Close()以后用命令netstat -a -n查看本地连接的时候对应的链接状态为 TIME_WAIT。该连接由系统自动关闭。