C#客户端

这是一个C#客户端程序,用于实现TCP/IP通信。它通过Socket类创建客户端,连接指定IP地址和端口,并在连接成功后开启新线程持续接收服务器发送的消息。当接收到消息时,会将其添加到列表框中显示。此外,客户端还有一个发送按钮,点击后可以将输入框中的消息发送给服务器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值