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 socket_client { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Socket tcpClient;//实例Socket Thread thrClient;//实例一个线程 private void btn_Connect_Click(object sender, EventArgs e) { //获取tbox_IP信息并转换为IP try { IPAddress IP = IPAddress.Parse(this.tbox_IP.Text.Trim()); IPEndPoint IP_Port = new IPEndPoint(IP, int.Parse(tbox_Port.Text.ToString().Trim())); this.tbox_Message.AppendText("正在连接服务器中...."+Environment.NewLine); //初始化tcpClient tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); tcpClient.Connect(IP_Port);//开始连接 } catch (Exception ex) { this.tbox_Message.AppendText("连接失败," + ex.Message + Environment.NewLine); return; } this.tbox_Message.AppendText("连接成功!" + Environment.NewLine); thrClient = new Thread(RcvMessage);//初始化线程 thrClient.IsBackground = true;//配置为后台线程; thrClient.Start();//启动线程; } private void RcvMessage() { while (true) { byte[] abyRcv = new byte[1024 * 1024 * 2]; int Length = tcpClient.Receive(abyRcv); if (Length == 0)//表示客户端已经断开了 { Invoke(new Action(() => this.tbox_Message.AppendText("断开连接" + Environment.NewLine))); } else { //byte数组转换为string类型; string strRcv = "接收:" + Encoding.UTF8.GetString(abyRcv, 0, Length) + "\r\n"; Invoke(new Action(() => this.tbox_Message.AppendText(strRcv))); } } } private void btn_Send_Click(object sender, EventArgs e) { try { //string类型转换为byte数组 byte[] abySend = Encoding.UTF8.GetBytes(tbox_SendData.Text.Trim()); tcpClient.Send(abySend); } catch (Exception ee) { this.tbox_Message.AppendText(ee.ToString()); return; } Invoke(new Action(() => this.tbox_Message.AppendText("发送:" + tbox_SendData.Text + "\r\n"))); } } }
标签:tbox,Socket,C#,IP,System,new,using,Message,客户端 From: https://www.cnblogs.com/csflyw/p/18419568