TCP协议

一。TCP协议

  1..TCP是面向连接的运输车协议

  2.每个TCOP只能有2个端点

  3.TCP提供可靠支付服务

  4.提供全双工通信

  5面向字节流

   二。按端口号可分为3大类

  (1)公认端口(WellKnownPorts):从0到1023,它们紧密绑定(binding)于一些服务。通常这些端口的通讯明确表明了某种服务的协议。例如:80端口实际上总是HTTP通讯。

  (2)注册端口(RegisteredPorts):从1024到49151。它们松散地绑定于一些服务。也就是说有许多服务绑定于这些端口,这些端口同样用于许多其它目的。例如:许多系统处理动态端口从1024左右开始。

  (3)动态和/或私有端口(Dynamicand/orPrivatePorts):从49152到65535。理论上,不应为服务分配这些端口。实际上,机器通常从1024起分配动态端口。

  

套接字 Scoket={ip地址,端口号}

TCP连接={scoket1,scoket2}={(ip,port),(ip2,port2)}

 

 

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Net;
  4 using System.Net.Sockets;
  5 using System.Text;
  6 using System.Threading;
  7 using System.Timers;
  8 using System.Windows.Forms;
  9 namespace sokectTest
 10 {
 11     public partial class Server : Form
 12     {
 13         public Server()
 14         {
 15             InitializeComponent();
 16         }
 17 
 18         private void Server_Load(object sender, EventArgs e)
 19         {
 20             Control.CheckForIllegalCrossThreadCalls = false;
 21             txtIP.Text = "127.0.0.1";
 22             txtPort.Text = "8001";
 23             this.Text = "服务端";
 24      
 25         }
 26         private void btnListen_Click(object sender, EventArgs e)
 27         {    
 28             IPAddress ip = IPAddress.Parse(txtIP.Text);
 29             IPEndPoint point=new IPEndPoint(ip,int.Parse(txtPort.Text));
 30             Socket sokect = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
 31             try
 32             {
 33                 sokect.Bind(point);
 34                 sokect.Listen(10);
 35                 ShowMsg("服务端开始监听");
 36                 Thread thread = new Thread(AcceptInfo);
 37                 thread.IsBackground = true;
 38                 thread.Start(sokect);
 39                 btnListen.Enabled = false;
 40 
 41             }
 42             catch (Exception exception)
 43             {
 44                 ShowMsg(exception.Message);
 45             }
 46         }
 47         Dictionary<string,Socket> dic=new Dictionary<string, Socket>();
 48         void AcceptInfo(object o)
 49         {
 50             Socket socket = o as Socket;
 51             while (true)
 52             {
 53                 try
 54                 {
 55                     Socket tSocket = socket.Accept();
 56                     string point = tSocket.RemoteEndPoint.ToString();//获取远程终结点
 57                     ShowMsg(point+"连接成功");
 58                     cbxRemoteItem.Items.Add(point);
 59                     dic.Add(point,tSocket);
 60                     //接受消息
 61                     Thread th=new Thread(ReceiverMsg);
 62                     th.IsBackground = true;
 63                     th.Start(tSocket);
 64 
 65                 }
 66                 catch (Exception exception)
 67                 {
 68                     ShowMsg(exception.Message);
 69                     break;
 70                 }
 71             }
 72        
 73         }
 74         void ReceiverMsg(object o)
 75         {
 76             Socket clientSocket = o as Socket;
 77             while (true)
 78               {
 79                 try
 80                 {
 81                     //存放客户端的数据
 82                     byte[] buffer = new byte[1024 * 1024];
 83                     //将接受过来的数据放到buffer中,并返回实际接受数据的长度
 84                     int length = clientSocket.Receive(buffer);
 85                     //将字节转换成字符串
 86                     string words = Encoding.UTF8.GetString(buffer, 0, length);
 87                     ShowMsg("收到客户端信息:");
 88                     ShowMsg(clientSocket.RemoteEndPoint.ToString() + ":" + words);
 89                
 90 
 91                 }
 92                 catch (Exception exception)
 93                 {
 94                     ShowMsg(exception.Message);
 95                     break;
 96                 }
 97               
 98             }
 99         }
100         private void btnSendMsg_Click(object sender, EventArgs e)
101           {   
102               SendMsg(txtInputMsg.Text);
103           }
104         private void ShowMsg(string msg)
105           {
106               txtLog.AppendText(msg+"\r\n");
107           }
108         private void txtInputMsg_KeyDown(object sender, KeyEventArgs e)
109           {
110 
111               if (e.KeyCode == Keys.Enter)
112               {
113                   SendMsg(txtInputMsg.Text);
114               }
115           }
116         public void SendMsg(string msg)
117           {
118               try
119               {
120                   if (string.IsNullOrEmpty(cbxRemoteItem.Text))
121                   {
122                       MessageBox.Show("请选择需要发送的客户端");
123                       return;
124                   }
125                   if (string.IsNullOrEmpty(msg.Trim()))
126                   {
127                       MessageBox.Show("发送的内容不能为空");
128                       return;
129                   }
130                   ShowMsg(txtInputMsg.Text);
131                   string ip = cbxRemoteItem.Text;
132                   byte[] buffer = Encoding.UTF8.GetBytes(txtInputMsg.Text);
133                   dic[ip].Send(buffer);
134                   txtInputMsg.Text = "";
135               }
136               catch (Exception exception)
137               {
138 
139                   ShowMsg(exception.Message);
140               }
141 
142           }
143         private void txtLog_TextChanged(object sender, EventArgs e)
144           {
145               txtLog.SelectionStart = txtLog.Text.Length;
146               txtLog.ScrollToCaret();
147           }
148  
149     }
150  }
服务端
  1 using System;
  2 using System.Net;
  3 using System.Net.Sockets;
  4 using System.Text;
  5 using System.Threading;
  6 using System.Windows.Forms;
  7 
  8 namespace SokectClient
  9 {
 10     public partial class Client : Form
 11     {
 12         public Client()
 13         {
 14             InitializeComponent();
 15         }
 16     
 17         private void Client_Load(object sender, EventArgs e)
 18         {
 19             this.Text = "客户端";
 20             Control.CheckForIllegalCrossThreadCalls = false;
 21             txtServerIP.Text = "127.0.0.1";
 22             txtServerPort.Text = "8001";
 23         
 24         }
 25         Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 26         private void btnConnect_Click(object sender, EventArgs e)
 27         {
 28 
 29             try
 30             {
 31                 IPAddress ip = IPAddress.Parse(txtServerIP.Text.Trim());
 32 
 33                 IPEndPoint point = new IPEndPoint(ip, int.Parse(txtServerPort.Text.Trim()));
 34                 clientSocket.Connect(point);
 35                 ShowMsg("连接成功");
 36                 ShowMsg("服务器" + clientSocket.RemoteEndPoint.ToString());
 37                 ShowMsg("客户端" + clientSocket.LocalEndPoint.ToString());
 38                 //连接后发送消息
 39                 Thread th = new Thread(ReceiveMsg);
 40                 th.IsBackground = true;
 41                 th.Start();
 42 
 43                
 44 
 45             }
 46             catch (Exception exception)
 47             {
 48 
 49                 ShowMsg(exception.Message);
 50             }
 51         }
 52         void ReceiveMsg()
 53         {
 54             while (true)
 55             {
 56                 try
 57                 {
 58                     byte[] buffer = new byte[1024 * 1024];
 59                     int length = clientSocket.Receive(buffer);
 60                     string s = Encoding.UTF8.GetString(buffer, 0, length);
 61                     ShowMsg(clientSocket.RemoteEndPoint.ToString() + ":" + s);
 62                  
 63                 
 64                 }
 65                   
 66                 catch (Exception exception)
 67                 {
 68                 ShowMsg(exception.Message);
 69                 break;
 70                 }
 71                
 72                
 73             }
 74         }
 75         private void ShowMsg(string msg)
 76         {
 77             txtLog.AppendText(msg + "\r\n");
 78         }
 79         private void btnSendMsg_Click(object sender, EventArgs e)
 80         {
 81             SendMsg(txtInputMsg.Text);
 82         }
 83         private void SendMsg(string msg)
 84         {
 85             try
 86             {
 87                 if (string.IsNullOrEmpty(msg.Trim()))
 88                 {
 89                     MessageBox.Show("发送的内容不能为空");
 90                     return;
 91                 }
 92                 if (clientSocket != null)
 93                 {
 94                     ShowMsg(msg);
 95                     byte[] buffer = Encoding.UTF8.GetBytes(msg);
 96                     clientSocket.Blocking = true;//解决无法立即完成一个非阻挡性套接字操作 的问题
 97                     clientSocket.Send(buffer);
 98                     txtInputMsg.Text = "";//清空输入的消息
 99                 }
100                 else
101                 {
102                     MessageBox.Show("请检查服务端是否连接?");
103                 }
104             }
105             catch (Exception exception)
106             {
107                 ShowMsg(exception.Message);
108             }
109         }
110         private void txtInputMsg_KeyDown(object sender, KeyEventArgs e)
111         {
112             if (e.KeyCode == Keys.Enter)
113             {
114                 SendMsg(txtInputMsg.Text);
115             }
116         }
117         private void txtLog_TextChanged(object sender, EventArgs e)
118         {
119             txtLog.SelectionStart = txtLog.Text.Length;
120             txtLog.ScrollToCaret();
121         }
122      
123     }
124 }
客户端

posted @ 2020-05-15 09:27  不科学的烤面筋  阅读(250)  评论(1)    收藏  举报