Net Core教程

C# Socket通信

本文主要是介绍C# Socket通信,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Socket简介

Socket又称套接字,它是处于应用层和传输层之间的一个抽象接口。它封装了TCP/UDP等的底层协议,通过它我们就可以实现应用程序或者进程之间(它们可以处在网络上的不同位置)的通信。

Socket的表示方法

因为Socket是两个程序之间的通信,只需要给定IP地址和端口号就可以进行通信。
Socket= (IP,PORT)

Socket(TCP)的工作流程


可以看到,总的工作流程就是:

  1. 服务端监听
  2. 客户端(可以有多个)请求连接
  3. 确认连接进行通信

针对服务器端的工作流程是:

  1. 建立Socket对象
  2. Bind(ip, port)绑定端口。比如说本地的(127.0.0.1, 6666)
  3. Listen()开始监听
  4. Accept()接受客户端连接
  5. Send()和Receive()进行通信
  6. Close()关闭套接字

而针对客户端的工作流程是:

  1. 建立Socket对象
  2. Connet(ip, port)向某个IP下的PORT端口发起连接请求,接受后开始通信
  3. Send()和Receive()进行通信
  4. Close() 关闭套接字

代码下载:https://github.com/urahyou/C-Sharp-Socket-example/tree/master

Server端代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace socket
{
    class Program
    {

        static Socket serverSocket;
       
        

        static void Main(string[] args)
        {
            SetListen();  //开始监听

        }

        static void SetListen()
        {
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                serverSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));
                serverSocket.Listen(2);

                Thread thread = new Thread(Listen);
                thread.Start(serverSocket);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            
        }

        static void Listen(object so)
        {
            Socket serverSocket = so as Socket;

            while (true)
            {
                try
                {
                    Socket clientSocket = serverSocket.Accept(); //接受客户端接入
                    // 获取链接IP地址
                    string clientPoint = clientSocket.RemoteEndPoint.ToString();

                    //开启新线程来不停接受信息
                    Thread rec = new Thread(Receive);
                    rec.Start(clientSocket);

                    //开启新线程来不停发送信息
                    Thread sen = new Thread(Send);
                    sen.Start(clientSocket);
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex.Message, ex);
                    break;
                }
            }
            serverSocket.Close();
        }

        static void Receive(object so)
        {
            Socket clientSocket = so as Socket;

            string clientPoint = clientSocket.RemoteEndPoint.ToString();
            while (true)
            {
                try
                {
                    byte[] buffer = new byte[1024];
                    int len = clientSocket.Receive(buffer);
                    //Console.WriteLine(len.ToString(), buffer);
                    if (len == 0) break;

                    string msg = Encoding.UTF8.GetString(buffer, 0, len);
                    Console.WriteLine("客户端说:"+ msg);
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
        }

        static void Send(object so)
        {
            Socket clientSocket = so as Socket;

            while (true)
            {
                //获取控制台输入
                string input = Console.ReadLine();

                byte[] msg = Encoding.UTF8.GetBytes(input);
                clientSocket.Send(msg);
            }
        }
    }
}

Client端代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;



namespace socket_client
{
    class Program
    {
        static Socket clientSocket;

        static void Main(string[] args)
        {
            
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            
            //连接
            Connect(); 
        }

        //连接客户端,连接后开始监听发送过来的消息并且把输入的信息发给服务端
        static void Connect()
        {
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
            
            try
            {
                //连接
                clientSocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));

                //独立线程来接受来自服务端的数据
                Thread receive = new Thread(Receive);
                receive.Start(clientSocket);

                //独立线程来发送数据给服务端
                Thread send = new Thread(Send);
                send.Start(clientSocket); 
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        static void Receive(object so)
        {
            Socket clientSocket = so as Socket;


            while (true)
            {
                Console.ForegroundColor = ConsoleColor.Green;  // 修改文字颜色为绿色
                try
                {
                    byte[] buffer = new byte[1024];
                    int len = clientSocket.Receive(buffer);
                    if (len > 0)
                    {
                        string msg = Encoding.UTF8.GetString(buffer);
                        
                        Console.WriteLine("服务端说:"+ msg);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    break;
                }
            }
            clientSocket.Close();
        }

        static void Send(object so)
        {
            Socket clientSocket = so as Socket;

            while (true)  // 监听键盘输入
            {
                Console.ForegroundColor = ConsoleColor.Red;
                //获取键盘输入
                string input = Console.ReadLine();
                //编码
                byte[] buffer = Encoding.UTF8.GetBytes(input);
                //发送
                clientSocket.Send(buffer);
            }
        }
    }
}

这篇关于C# Socket通信的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!