C#版 Winform界面 Socket编程 Client客户端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
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 _07Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Socket socketSend;
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                //创建负责通信的Socket
                socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Parse(txtServer.Text);
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
                //获得要连接的远程服务器应用程序的IP地址和端口号
                socketSend.Connect(point);
                ShowMsg("连接成功");

                //开启一个新的线程不停的接收服务端发来的消息
                Thread th = new Thread(Recive);
                th.IsBackground = true;
                th.Start();
            }
            catch
            { }

        }


        /// <summary>
        /// 不停的接受服务器发来的消息
        /// </summary>
        void Recive()
        {
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024 * 1024 * 3];
                    int r = socketSend.Receive(buffer);
                    //实际接收到的有效字节数
                    if (r == 0)
                    {
                        break;
                    }
                    //表示发送的文字消息
                    if (buffer[0] == 0)
                    {
                        string s = Encoding.UTF8.GetString(buffer, 1, r-1);
                        ShowMsg(socketSend.RemoteEndPoint + ":" + s);
                    }
                    else if (buffer[0] == 1)
                    {
                        SaveFileDialog sfd = new SaveFileDialog();
                        sfd.InitialDirectory = @"C:\Users\SpringRain\Desktop";
                        sfd.Title = "请选择要保存的文件";
                        sfd.Filter = "所有文件|*.*";
                        sfd.ShowDialog(this);
                        string path = sfd.FileName;
                        using (FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
                        {
                            fsWrite.Write(buffer, 1, r - 1);
                        }
                        MessageBox.Show("保存成功");
                    }
                    else if (buffer[0] == 2)
                    {
                        ZD();
                    }

                }
                catch { }

            }
        }




        /// <summary>
        /// 震动
        /// </summary>
        void ZD()
        {
            for (int i = 0; i < 500; i++)
            {
                this.Location = new Point(200, 200);
                this.Location = new Point(280, 280);
            }
        }



        void ShowMsg(string str)
        {
            txtLog.AppendText(str + "\r\n");
        }

        /// <summary>
        /// 客户端给服务器发送消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            string str = txtMsg.Text.Trim();
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
            socketSend.Send(buffer);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }
    }
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WinForms中使用Socket建立TCP/IP客户端,可以按照以下步骤进行: 1. 引入System.Net.Sockets命名空间,因为Socket类位于该命名空间下。 2. 创建Socket对象,指定协议族、套接字类型和协议类型。 ``` Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ``` 3. 创建服务器的IP地址和端口号,并通过客户端套接字的Connect方法连接到服务器。 ``` IPAddress serverIP = IPAddress.Parse("192.168.0.100"); int serverPort = 8888; clientSocket.Connect(new IPEndPoint(serverIP, serverPort)); ``` 4. 发送数据到服务器。 ``` string message = "Hello, Server!"; byte[] data = Encoding.UTF8.GetBytes(message); clientSocket.Send(data); ``` 5. 接收服务器发送的数据。 ``` byte[] buffer = new byte[1024]; int length = clientSocket.Receive(buffer); string message = Encoding.UTF8.GetString(buffer, 0, length); ``` 6. 关闭客户端套接字。 ``` clientSocket.Close(); ``` 完整代码示例: ``` using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Windows.Forms; namespace Example { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { try { // 创建客户端套接字 Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 连接到服务器 IPAddress serverIP = IPAddress.Parse("192.168.0.100"); int serverPort = 8888; clientSocket.Connect(new IPEndPoint(serverIP, serverPort)); // 发送数据到服务器 string message = "Hello, Server!"; byte[] data = Encoding.UTF8.GetBytes(message); clientSocket.Send(data); // 接收服务器发送的数据 byte[] buffer = new byte[1024]; int length = clientSocket.Receive(buffer); string message = Encoding.UTF8.GetString(buffer, 0, length); // 关闭客户端套接字 clientSocket.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } ``` 注意:在实际使用中,需要根据具体情况进行异常处理、多次发送或接收数据等操作,以保证TCP/IP客户端的正常运行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值