![]()
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 SocketClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();//初始化部件
}
Socket Socket_0;//声明一个Socket;
Thread Thread_0; //声明一个Thread线程
private void btn_Connect_Click(object sender, EventArgs e)//点击连接事件
{
if (btn_Connect.Text=="连接")
{
try
{
IPAddress IPAddress_0 = IPAddress.Parse(this.tbox_IP.Text.Trim()); //将输入框内容转换为IPAddress类型
IPEndPoint IPEndPoint_0 = new IPEndPoint(IPAddress_0, int.Parse(tbox_Port.Text.Trim()));//声明一个IPEndPoint(IP+端口号)
Socket_0 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.tbox_Message.AppendText("正在连接服务器中..."+"\r\n");
Socket_0.Connect(IPEndPoint_0);//连接服务器
this.tbox_Message.AppendText("连接成功" + "\r\n");//tbox_Message中提示<连接成功>;
btn_Connect.Text = "断开";
Thread_0 = new Thread(thrRcvMessage);
Thread_0.IsBackground = true;//后台线程;
Thread_0.Start();
}
catch (Exception ex)
{
this.tbox_Message.AppendText("连接程序异常:" + ex.Message + "\r\n");//tbox_Message中提示<连接失败+失败信息>;
return;
}
}
else if(btn_Connect.Text=="断开")
{
Socket_0.Close();//断开服务器连接;
this.tbox_Message.AppendText("已断开" + "\r\n");//提示信息<已断开>
btn_Connect.Text = "连接";
Thread_0.Abort();
}
}
private void thrRcvMessage()//接收数据的后台线程
{
while (true)
{
try
{
byte[] abyRcv = new byte[1024];
int iLength = Socket_0.Receive(abyRcv);
if (iLength == 0)//表示客户端已经断开
{
Invoke(new Action(() => this.tbox_Message.AppendText("服务器连接断开!" + "\r\n")));//提示<服务器连接断开>
Invoke(new Action(() => Socket_0.Close()));//关闭Socket
Invoke(new Action(() => this.btn_Connect.Text = "连接"));//修改连接按钮text
break;
}
else
{
string strRcv = Encoding.UTF8.GetString(abyRcv, 0, iLength);//编码转换:字节数组→字符串
Invoke(new Action(() => this.tbox_Message.AppendText("接收:" + strRcv + "\r\n")));//提示信息:接收内容
Invoke(new Action(() => this.tbox_RcvData.Text = ""));//接收框内容清空
Invoke(new Action(() => this.tbox_RcvData.AppendText(strRcv)));//接收框内容输出
}
}
catch (Exception)
{
Invoke(new Action(() => this.tbox_Message.AppendText("接收程序异常!" + "\r\n")));//提示<>;
return;
}
}
}
private void btn_Send_Click(object sender, EventArgs e)//点击发送事件
{
try
{
if (btn_Connect.Text == "断开")//通信已连接
{
byte[] abySend = Encoding.UTF8.GetBytes(tbox_SendData.Text.Trim());//将tbox_SendData中的数据转化为字节类数组;
Socket_0.Send(abySend);//发送数据
tbox_Message.AppendText("发送:" + tbox_SendData.Text + "\r\n");//信息显示:<发送数据>
}
else
{
tbox_Message.AppendText("服务器未连接!" + "\r\n");
}
}
{
catch (Exception ee)
tbox_Message.AppendText("发送程序异常!" + ee.Message + "\r\n");
return;
}
}
}
}