C# Socket simple application

 

 Socket basics

server (console )

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

namespace Test_SocketServer
{
    class Program
    {
        static void Main(string[] args)
        {
            //1、创建服务端Socket对象(负责监听客户端连接)
            Socket ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPAddress ipaddress = IPAddress.Parse("127.0.0.1");
            EndPoint endpoint = new IPEndPoint(ipaddress,8055);

            //2、绑定IP和端口
            ServerSocket.Bind(endpoint);
            Console.WriteLine("服务器启动成功....");
            //3、监听
            ServerSocket.Listen(100);
            Console.WriteLine("开始监听....");
            while (true)
            {
                //4、等待接收客户端连接(返回用于和客户端通信的Socket)
                Socket newSocket = ServerSocket.Accept();
                Console.WriteLine("连接到一个客户端:", newSocket.RemoteEndPoint);
                byte[] data = new byte[1024];
                //5、接收消息
                newSocket.Receive(data);
                //6、发送
                newSocket.Send(data);
                //7、关闭
                newSocket.Close();
            }
        }
    }
}

client (console )

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

namespace Socket_ClientTCP
{
    class Program
    {
        static void Main(string[] args)
        {
            //1、创建一个Socket对象(和服务端进行通信)
            Socket ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //2、连接服务器
            EndPoint endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8055);
            ClientSocket.Connect(endpoint);

            byte[] data = new byte[1024];
            //3、发送
            ClientSocket.Send(data);
            //4、接收
            ClientSocket.Receive(data);
            5、关闭Socket
            //ClientSocket.Close();
        }
    }
}

Simple Communication (Console and Unity)

WithClient class (console )

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

namespace FuWuDuan
{
    class WithClient
    {
        Thread thread;
        private Socket WithClientSocket;
        byte[] data = new byte[1024];

        //返回客户端状态
        public bool isConnection 
        {
            get 
            {
                return WithClientSocket.Connected;
            }
        }

        public WithClient(Socket clientSocket)
        {
            WithClientSocket = clientSocket;

            //启动一个线程
            thread = new Thread(ReceivMessage);
            thread.Start();
        }

        private void ReceivMessage()
        {
            while (true)
            {
                //5、接收消息
                int length = WithClientSocket.Receive(data);
                string ReMsg = Encoding.UTF8.GetString(data, 0, length);

                //广播到客户端
                Program.BroadcastMessage(ReMsg);
                Console.WriteLine("接收客户端发送的消息" + ReMsg);
                6、发送
                //newSocket.Send(data);
                7、关闭
                //newSocket.Close();
            }
        }
        //发送消息
        public void SendMessage(string message) 
        {
            byte[] data = Encoding.UTF8.GetBytes(message);
            WithClientSocket.Send(data);
        }
    }
}

Program class (console )

using System;
using System.Net.Sockets;
using System.Net;
using System.Collections.Generic;

namespace FuWuDuan
{
    class Program
    {
        static Socket ServerSocket; //Socket属性
        static EndPoint endPoint; //地址和端口属性

        static string address = "127.0.0.1";//IP地址
        static int port = 8055;//端口
        static int num = 100;//客户端连接数量

        //存放连接的客户端对象
        public static List<WithClient> ListWithClient = new List<WithClient>();




        static void Main(string[] args)
        {
            //1、创建服务端Socket对象(负责监听客户端连接)
            ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            endPoint = new IPEndPoint(IPAddress.Parse(address), port);

            //2、绑定监听端口
            ServerSocket.Bind(endPoint);
            Console.WriteLine("服务器启动成功.....");

            //3、设置监听队列
            ServerSocket.Listen(num);
            Console.WriteLine("开始监听.....");

            while (true)
            {
                //4、连接一个新的客户端(返回用于和客户端通信的Socket)
                Socket newSocket = ServerSocket.Accept();
                Console.WriteLine("连接到一个客户端", newSocket.RemoteEndPoint);
                //创建一个与客户端通信对象
                WithClient withClient = new WithClient(newSocket);
                ListWithClient.Add(withClient); 
            }
        }

        //向服务端广播消息
        public static void BroadcastMessage(string message)
        {
            //断开连接的客户端存放到List中
            List<WithClient> newWithClient = new List<WithClient>();
            for (int i = 0; i < ListWithClient.Count; i++)
            {
                if (ListWithClient[i].isConnection)
                {
                    //广播还在连接中的客户端
                    ListWithClient[i].SendMessage(message);
                }
                else
                {
                    //存放断开连接的客户端
                    newWithClient.Add(ListWithClient[i]);
                }
            }
            //断开连接则移除
            for (int i = 0; i < newWithClient.Count; i++)
            {
                ListWithClient.Remove(newWithClient[i]);
            }
        }
        
    }
}

Client (Unity)

using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using System.Threading;

public class Test : MonoBehaviour
{
    public static Socket ClientSocket;
    EndPoint endpoint;
    byte[] data;

    public Text text;
    void Start()
    {
        //1、创建一个Socket对象(和服务端进行通信)
        ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //2、连接服务器
        data = new byte[1024];
        endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8055);
        ClientSocket.Connect(endpoint);



        //4、接收消息
        Thread thread = new Thread(ReceiveMessage);
        thread.Start();
        //5、关闭Socket
    }
    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            //3、发送消息
            SendMessage2(text.text);

        }
    }

    //3、发送
    public static void SendMessage2(string message)
    {
        byte[] data = Encoding.UTF8.GetBytes(message);
        ClientSocket.Send(data);
    }

    public static byte[] datas = new byte[2048];
    //4、接收
    public static void ReceiveMessage()
    {
        int length = ClientSocket.Receive(datas);
        string ReMsg = Encoding.UTF8.GetString(datas, 0, length);

        System.Console.WriteLine("接收到服务端发送的消息:" + ReMsg);
    }
}

Socket asynchronous

Server

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


namespace ServerSocket
{
    class Program
    {
        private static Socket socket;
        private static byte[] buffer = new byte[1024];
        static void Main(string[] args)
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(new IPEndPoint(IPAddress.Any, 6666));
            socket.Listen(0);
            StartAccept();
            Console.Read();
        }
        static void StartAccept() 
        {
            socket.BeginAccept(AcceptCallback, null);
        }

        static void StartReceive(Socket client) 
        {
            client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, client);
        }

        static void ReceiveCallback(IAsyncResult iar) 
        {
            Socket client = iar.AsyncState as Socket;
            int len = client.EndReceive(iar);
            if (len == 0) return;
            string str = Encoding.UTF8.GetString(buffer, 0, len);
            Console.WriteLine(str);
            StartReceive(client);
        }

        static void AcceptCallback(IAsyncResult iar) 
        {
            Socket client = socket.EndAccept(iar);
            StartReceive(client);
            StartAccept();
        }
    }
}

client

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System;
using System.Text;

public class Client : MonoBehaviour
{
    private Socket socket;
    private byte[] buffer = new byte[1024];
    void Start()
    {
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        socket.Connect("127.0.0.1", 6666);//连接服务端
        StartReceive(); //异步接收消息
        Send();
    }
    //异步接收消息
    void StartReceive() 
    {
        //异步接收消息
        socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, null);
    }
    //异步接收消息回调
    void ReceiveCallback(IAsyncResult iar) 
    {
        int len = socket.EndReceive(iar);//返回一个消息长度
        if (len == 0) return;//如果长度为0则不解析
        string str = Encoding.UTF8.GetString(buffer, 0, len);
        Debug.Log(str);
        StartReceive();
    }

    void Send() 
    {
        socket.Send(Encoding.UTF8.GetBytes("你好!"));
    }

    void Update()
    {
        
    }
}

Guess you like

Origin blog.csdn.net/weixin_46711336/article/details/126391531