让代码更简单

C#Socket套接字使用Tcp协议通信(客户端)

重要:本文最后更新于2018-11-13 13:53:56,某些文章具有时效性,若有错误或已失效,请在下方留言或联系代码狗

上一篇实现了服务器端的sockets编程,下面是客户端的程序,运行效果如下:

c#socket通信实例

c#socket通信实例

开启服务器之后,填上服务器地址与端口,点击即可连接,笔者在两台工控机之间测试正常通信。

服务器端代码:C#Socket套接字使用Tcp协议通信(服务器端)

下面是客户端的源代码,比起服务器端来说,客户端的代码简洁不少。

复制
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace client
{
 public partial class Form1 : Form
 {
 public delegate void upadta (String arg);
 Socket mysocket;
 public Form1 ()
 {
 InitializeComponent ();
 }

private void Form1_Load ( object sender, EventArgs e )
 {

}

private void button1_Click ( object sender, EventArgs e )
 {
 
 mysocket = new Socket ( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
 IPAddress ips = IPAddress.Parse ( textBox1.Text );
 IPEndPoint ipend = new IPEndPoint ( ips, Convert.ToInt16 ( textBox2.Text ) );
 mysocket.Connect ( ipend );
 Thread thread = new Thread ( resmessg );
 thread.IsBackground = true;
 thread.Start ();
 
 }
 public void resmessg (object obj)
 {
 upadta day = new upadta (updataui);
 while(true){
 byte[] mess = new byte[1024 * 1024];
 int length = mysocket.Receive (mess);
 String dtr = Encoding.UTF8.GetString (mess,0,length);
 Invoke (day,dtr);
 }
 }

private void button2_Click ( object sender, EventArgs e )
 {
 byte[] senstr = Encoding.UTF8.GetBytes (textBox3.Text.ToString());
 mysocket.Send (senstr);
 textBox4.Text += textBox3.Text;
 textBox3.Text = "";
 }
 public void updataui (String arg)
 {
 textBox4.Text += arg;
 }
 }
}

客户端同样用到了委托,此代码仅供参考。笔者在vs2012net4.5环境中编译通过。下面附上项目代码

感觉很棒!可以赞赏支持我哟~

16 打赏

评论 (0)

登录后评论
QQ咨询 邮件咨询 狗哥推荐