于梦想齐行
于梦想齐行

C#同步Socket Client(Windows Form)

C#同步Socket Client(Windows Form)

库文件(SocketLib.cs)

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace WindowsFormsApp3
{
    public class SocketLib
    {
        private static byte[] buffer = new byte[1024*100];
        public static string Get()
        {
            string message = "";
            try
            {
                //获取hostname的ip地址集,本机地址可使用Dns.GetHostName()
                IPHostEntry ipHostInfo = Dns.GetHostEntry("www.baidu.com");
                //使用获取到的第一个地址
                IPAddress ipAddress = ipHostInfo.AddressList[0];
                //设置终结点的ip地址和端口
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, 80);//ip port
                Socket st = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    //连接
                    st.Connect(remoteEP);
                    message += "Socket connected to " + st.RemoteEndPoint.ToString()+"\r\n";
                    //发送
                    byte[] msg = Encoding.UTF8.GetBytes("GET / HTTP/1.1\r\n\r\nHost: www.baidu.com\r\nAccept: */*\r\n\r\n");
                    int bytesSent = st.Send(msg);
                    int bytesRecv;
                    //接收,这里只是简单的判断,并没有从HTTP头部中获取正文长度,仅供演示
                    do
                    {
                        bytesRecv = st.Receive(buffer);
                        message += Encoding.UTF8.GetString(buffer, 0, bytesRecv) + "\r\n";
                    } while (bytesRecv > 0);
                    //关闭
                    st.Shutdown(SocketShutdown.Both);
                    st.Close();
                }
                catch (ArgumentNullException ane)
                {
                    message += "ArgumentNullException: " + ane.ToString() + "\r\n";
                }
                catch (SocketException se)
                {
                    message += "SocketException: " + se.ToString() + "\r\n";
                }
                catch (Exception e1)
                {
                    message += "Exception: " + e1.ToString() + "\r\n";
                }
            }
            catch (Exception e2)
            {
                message += e2.ToString() + "\r\n";
            }
            return message;
        }
    }
}

主程序(Form1.cs)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {
        //主线程上下文
        public SynchronizationContext mainThreadContext;
        public Form1()
        {
            mainThreadContext = SynchronizationContext.Current;
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.textBox1.Text = "Start!\r\n";
            //将Socket操作放在子线程
            ThreadStart ts = new ThreadStart(ThreadGet);
            Thread th = new Thread(ts);
            th.Start();
        }

        void showText(object text)
        {
            var str = text as string;
            this.textBox1.Text += str;
        }

        void ThreadGet()
        {
            string message = So.Get();
            //将信息送回主线程
            mainThreadContext.Post(new SendOrPostCallback(showText), message);
        }
    }
}

参阅

https://docs.microsoft.com/zh-cn/dotnet/framework/network-programming/synchronous-client-socket-example

#
首页      CSharp      C#同步Socket Client(Windows Form)

于梦想齐行

C#同步Socket Client(Windows Form)
库文件(SocketLib.cs) using System; using System.Text; using System.Net; using System.Net.Sockets; namespace WindowsFormsApp3 { public class SocketLib { …
扫描二维码继续阅读
2022-07-01
近期文章
近期评论