.NET网络通信基础Socket编程

Java
420
0
0
2022-07-31

Socket的由来

Socket的概念最早由Berkeley UNIX提出;

专门用来处理在网络上传输数据的过程;

Socket自提出以来一直就是网络应用程序最重要且应用最为广泛的技术;

通过Socket概念进行网络联机,可以避免处理切割数据封包、分段传输与数据重组等繁复的细节

引用Socket

System.Net.Sockets命名空间主要包括Sockets网络通信应用程序的相关类:

Socket类

TCPClient类

TCPListener类(监听)

UDPClient类

NetworkStream类(通讯过程中,进行流化转换的一个类)

SocketException类

Socket类的方法

Bind方法(服务器的ip地址和端口号绑定)

Accept方法(服务端接受客户端请求)

Connect方法(客户端请求服务点)

Send方法和SendTo方法

Receive方法和ReceiveFrom方法(接受对方传送信息)

Close方法和Shutdown方法(关闭连接)

接下去我们通过一个服务端和客户端的例子来了解一下Socket带给我们的便捷

我们先看一下效果图 , 当服务端启动后 , 客户端填写和服务端相同的端口号 , 并且把服务端的IP地址填写正确 , 就达到了我们今天的效果

.NET网络通信基础Socket编程

服务端代码

public partial class Server : Form
{
    delegate void ControlChangeHandler(string msg1,string msg2);
    private int port;
    private Socket mySocket;
    private Socket myAcceptSocket;
    public Server()
    {
        InitializeComponent();
    }
    private void StartListen()
    {
        port = Convert.ToInt32(this.txtPort.Text.Trim());
        try
        {
            mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            mySocket.Bind(new IPEndPoint(IPAddress.Parse("本机IP地址"),port ));
            mySocket.Listen(10);
            string msg = "等待Socket客户联机中...";
            this.Invoke(new ControlChangeHandler(this.onChange), new object[] {msg,"" });
        }
        catch (SocketException ex)
        {
            MessageBox.Show(ex.Message );
        }
    }
    private void Accept()
    {
        byte[] data = new byte[1024];
        int length;
        try
        {
            string msg = "开始接受客户端的联机请求,接收联机信息......";
            this.Invoke(new ControlChangeHandler(this.onChange),new object[]{msg,""});
            myAcceptSocket = mySocket.Accept();
            length = myAcceptSocket.Receive(data );
            msg = "接收了" + length.ToString() + "个字节的数据";
            string msg1 = Encoding.UTF8.GetString(data);
            this.Invoke(new ControlChangeHandler(this.onChange ),new object[]{msg,msg1});
        }
        catch(SocketException ex)
        {
            MessageBox.Show(ex.Message );
        }
    }
    private void onChange(string msg1, string msg2)
    {
        if (msg1 != "")
        {
            this.txtConnection.Text += msg1 + "\r\n";
        }
        if (msg2 != "")
        {
            this.txtAccept.Text += msg2 + "\r\n";
        }
    }
    private void btnListen_Click(object sender, EventArgs e)
    {
        Thread th = new Thread(new ThreadStart(this.StartListen));
        th.IsBackground = true;
        th.Start();
    }
    private void btnAccept_Click(object sender, EventArgs e)
    {
        Thread th = new Thread(new ThreadStart(this.Accept ));
        th.IsBackground = true;
        th.Start();
    }
}

客户端代码

public partial class Client : Form
{
    delegate void ControlChangeHandler(string msg1, string msg2);
    int port;
    IPAddress address;
    private Socket mySocket;
    public Client()
    {
        InitializeComponent();
    }
    private void StartConnection()
    {
        port = Convert.ToInt32(this.txtPort.Text.Trim());
        address = IPAddress.Parse(this.txtAddress.Text.Trim());
        try
        {
            mySocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp );
            mySocket.Connect(address,port );
            //mySocket.Connect(new IPEndPoint(address,port ));  
            string msg = "联机至远程Socket.........";
            this.Invoke(new ControlChangeHandler(this.onChange), new object[] { msg,""});
        }
        catch (SocketException ex)
        {
            MessageBox.Show(ex.Message );
        }
    }
    private void Send()
    {
        byte[] data=new byte[1024];
        int length;
        try
        {
            data = Encoding.ASCII.GetBytes(this.txtSend.Text.Trim() );
            length = mySocket.Send(data);
            string msg = "传送了" + length.ToString() + "字节的数据";
            this.Invoke(new ControlChangeHandler(this.onChange), new object[] { msg, "" });
        }
        catch (SocketException ex)
        {
            MessageBox.Show(ex.Message );
        }
    }
    private void onChange(string msg1, string msg2)
    {
        if (msg1 != "")
        {
            this.txtConnection.Text += msg1 + "\r\n";
        }
        if (msg2 != "")
        {
            this.txtSend.Text += msg2 + "\r\n";
        }
    }
    private void btnConnection_Click(object sender, EventArgs e)
    {
        Thread th = new Thread(new ThreadStart(this.StartConnection ));
        th.IsBackground = true;
        th.Start();
    }
    private void btnSend_Click(object sender, EventArgs e)
    {
        Thread th = new Thread(new ThreadStart(this.Send ));
        th.IsBackground = true;
        th.Start();
    }
}