using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace csharp_Client
{
public partial class Client : Form
{
public Client()
{
InitializeComponent();
///多线程编程中,如果子线程需要使用主线程中创建的对象和控件,最好在主线程中体现进行检查取消
CheckForIllegalCrossThreadCalls = false;
}
/// 创建客户端
private Socket client;
private void button_connect_Click(object sender, EventArgs e)
{
///创建客户端
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
///IP地址
IPAddress ip = IPAddress.Parse(textBox_address.Text);
///端口号
IPEndPoint endPoint = new IPEndPoint(ip, int.Parse(textBox_port.Text));
///建立与服务器的远程连接
try
{
client.Connect(endPoint);
}
catch(Exception)
{
MessageBox.Show("地址或端口错误!!!!");
return;
}
///线程问题
Thread thread = new Thread(ReciveMsg);
thread.IsBackground = true;
thread.Start(client);
}
/// 客户端接收到服务器发送的消息
private void ReciveMsg(object o)
{
Socket client = o as Socket;
while (true)
{
try
{
///定义客户端接收到的信息大小
byte[] arrList = new byte[1024 * 1024];
///接收到的信息大小(所占字节数)
int length = client.Receive(arrList);
string msg = DateTime.Now + Encoding.UTF8.GetString(arrList, 0, length);
listBox_log.Items.Add(msg);
}
catch (Exception)
{
///关闭客户端
client.Close();
}
}
}
/// 客户端发送消息给服务端
private void button_send_Click(object sender, EventArgs e)
{
if (textBox_message.Text != "")
{
SendMsg(textBox_message.Text);
}
}
/// 客户端发送消息,服务端接收
private void SendMsg(string str)
{
byte[] arrMsg = Encoding.UTF8.GetBytes(str);
client.Send(arrMsg);
}
private void Client_FormClosed(object sender, FormClosedEventArgs e)
{
if(client!=null) client.Close();
}
}
}
C#客户端
最新推荐文章于 2021-11-27 20:46:56 发布