区块链技术博客
www.b2bchain.cn

C# Socket编程 客户端 与 服务器

这篇文章主要介绍了C# Socket编程 客户端 与 服务器的讲解,通过具体代码实例进行16749 讲解,并且分析了C# Socket编程 客户端 与 服务器的详细步骤与相关技巧,需要的朋友可以参考下https://www.b2bchain.cn/?p=16749

本文实例讲述了2、树莓派设置连接WiFi,开启VNC等等的讲解。分享给大家供大家参考文章查询地址https://www.b2bchain.cn/7039.html。具体如下:

tcp Socket编程

  • 服务器
  • 客户端
  • 服务器代码
  • 客户端代码

服务器

1、创建套接字Socket,用于监听
2、绑定Bind
3、监听Listen
4、等待连接Accept,得到通信套接字Socket
5、使用通信套接字,发送接收数据Send Recevie

C# Socket编程 客户端 与 服务器

客户端

1、创建套接字 Soctket
2、建立连接 Connect
3、发送接收数据Send Recevie

C# Socket编程 客户端 与 服务器

服务器代码

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms;  namespace TcpSocket {     public partial class Tcp : Form     {          bool IsOpenClose = false;         Socket socketRecive = null;         Socket socketListen = null;         public Tcp()         {             InitializeComponent();         }          private void button_OpenClose_Click(object sender, EventArgs e)         {              IsOpenClose = !IsOpenClose;             if (IsOpenClose)             {                 button_OpenClose.Text = "关闭";                 try                 {                     //1、创建套接字                     socketListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                     //2、初始化IP 端口                     IPAddress ip = IPAddress.Any;// IPAddress.Parse(string);也可通过textbox获取                     IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(textPort.Text));                      //3、绑定套接字                     socketListen.Bind(point);                     //4、监听套接字                     socketListen.Listen(5);                  }                 catch                 {                     button_OpenClose.Text = "开始";                     if (socketListen != null)                     {                         socketListen.Close();                     }                 }                  showMessage("监听中.........");                  //5、与客户端建立连接(线程)                 Thread Getmessage = new Thread(GetReciveMessage);                 Getmessage.IsBackground = true;                 Getmessage.Start(socketListen);             }             else             {                 button_OpenClose.Text = "开始";                 if(socketListen != null)                 {                     socketListen.Close();                 }                                 if (socketRecive != null)                 {                                   socketRecive.Close();                 }              }         }         private void showMessage(string str)         {             textReceive.AppendText(str);             textReceive.AppendText("n");         }         private void GetReciveMessage(object obj)         {             Socket socketL = obj as Socket;             try             {                 while (true)                 {                     socketRecive = socketL.Accept();                     showMessage("连接成功.........");                     Thread thrReceive = new Thread(ReceiveDate);                     thrReceive.IsBackground = true;                     thrReceive.Start(socketRecive);                 }             }             catch             {                 if (socketRecive != null)                 {                                        socketRecive.Close();                 }             }          }         private void ReceiveDate(object o)         {             Socket socketRecive = o as Socket;             try             {                 while (true)                 {                     byte[] buf = new byte[1024 * 1024 * 2];                     int countbuf = socketRecive.Receive(buf);                     if (countbuf == 0)                     {                         socketListen.Shutdown(SocketShutdown.Both);                         socketRecive.Close();                         break;                     }                     else                     {                         string str = Encoding.Default.GetString(buf, 0, countbuf);                         showMessage(socketRecive.RemoteEndPoint.ToString() + ":" + str );                     }                  }             }             catch             {                          socketRecive.Close();             }          }          private void Tcp_FormClosed(object sender, FormClosedEventArgs e)         {             this.Owner.Show();         }          private void Tcp_Load(object sender, EventArgs e)         {             Control.CheckForIllegalCrossThreadCalls = false;         }          private void button_Send_Click(object sender, EventArgs e)         {             string str = textSend.Text;             byte[] buf = new byte[1024 * 1024 * 2];             buf = Encoding.Default.GetBytes(str);             try             {                 socketRecive.Send(buf);                 textSend.Text = null;             }             catch             {                 MessageBox.Show("发送失败");             }                      }     } }  

客户端代码

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms;  namespace ClientSocket {     public partial class Client : Form     {         private bool IsConnection = false;         private Socket socketConnect = null;         public Client()         {             InitializeComponent();         }          private void buttonConnect_Click(object sender, EventArgs e)         {             IsConnection = !IsConnection;             if (IsConnection)             {                 try                 {                     buttonConnect.Text = "断开";                     socketConnect = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                     IPAddress ip = IPAddress.Parse(textBoxIP.Text);                     IPEndPoint port = new IPEndPoint(ip, Convert.ToInt32(textBoxPort.Text));                     socketConnect.Connect(port);                     showMessage("连接成功");                      Thread RecieveDateThr = new Thread(RecieveDate);                     RecieveDateThr.IsBackground = true;                     RecieveDateThr.Start(socketConnect);                 }                 catch                 {                                   buttonConnect.Text = "连接";                     showMessage("连接断开......");                     if (socketConnect != null)                     {                         //socketConnect.Shutdown(SocketShutdown.Both);                         socketConnect.Close();                     }                            }               }             else             {                 buttonConnect.Text = "连接";                 if (socketConnect != null)                 {                     socketConnect.Close();                 }             }          }          private void RecieveDate(object o)         {             Socket socket = o as Socket;             try             {                 while (true)                 {                     byte[] buf = new byte[1024 * 1024 * 2];                     int count1 = socket.Receive(buf);                                          if (count1 == 0)                     {                         break;                     }                     else                     {                                                string str = Encoding.Default.GetString(buf, 0, count1);                         showMessage(str);                      }                 }             }             catch             {                         MessageBox.Show("RecieveDate中While有问题");             }          }          private void showMessage(string str)         {             textReceive.AppendText(str);             textReceive.AppendText("n");         }          private void buttonSend_Click(object sender, EventArgs e)         {             string strSend = textSend.Text;             var buf = new byte[1024 * 1024 * 2];             //int i = 0;             //foreach (var n in strSend)             //{             //    buf[i++] = (byte)n;             //}             buf = Encoding.Default.GetBytes(strSend);             try             {                 socketConnect.Send(buf);                 textSend.Text = null;             }             catch             {                 buttonConnect.Text = "连接";              }                      }          private void Client_FormClosed(object sender, FormClosedEventArgs e)         {             if (socketConnect != null)             {                 socketConnect.Close();                 socketConnect = null;             }         }          private void Client_Load(object sender, EventArgs e)         {                          Control.CheckForIllegalCrossThreadCalls = false;         }     } }  

本文转自互联网,侵权联系删除C# Socket编程 客户端 与 服务器

赞(0) 打赏
部分文章转自网络,侵权联系删除b2bchain区块链学习技术社区 » C# Socket编程 客户端 与 服务器
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

b2b链

联系我们联系我们