C#——Socket编程

IP地址操作类

IPAddress类
在该类中有一个Parse()方法,可以把点分的十进制IP转化成IPAddress类
示例:
IPAddress address = IPAddress.Parse(192.168.0.1);

IPEndPoint类
IPEndPoint其实就是一个IP地址和端口的绑定,可以代表一个服务,用来Socket通讯

TCP的Scoket编程,主要分两部分:

一、服务端Socket侦听:

  1. 创建IPEndPoint实例,用于Socket侦听时绑定;
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 6001);
  1. 创建套接字实例
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

这里创建的时候用ProtocolType.Tcp,表示建立一个面向连接(TCP)的Socket。

  1. 将所创建的套接字与IPEndPoint绑定
serverSocket.Bind(ipep); 
  1. 设置套接字为接听模式
 serverSocket.Listen(10); 

通过以上四步,我们已经建立了Socket的侦听模式,下面我们就来设置怎么样获取客户Socket连接的实例,以及连接后的信息发送。

  1. 在套接字上接收接入的连接

  2. 在套接字上接受客户端发送的信息和发送信息

二、服务端Socket侦听:

  1. 创建IPEndPoint实例和套接字
    IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6001); 
    clientSocket = new  Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  1. 将套接字连接到远程服务器
try{
    clientSocket.Connect(ipep);
    }
catch(SocketException ex)
    {
    MessageBox.Show("connect error:" + ex.Message;)
    return;
}
  1. 接受消息
    while (true)
    {  
    int bufLen = 0;
    try 
    {                       
    bufLen = clientSocket.Available;                          
    clientSocket.Receive(data, 0, bufLen, SocketFlags.None);                     
    if (bufLen == 0)                    
        { 
        continue; 
        }              
    }                
    catch (Exception ex)                 
    { MessageBox.Show("Receive Error:" + ex.Message);  
    return;              
    }             
    string clientcommand = System.Text.Encoding.ASCII.GetString(data).Substring(0, bufLen); 
    lstClient.Items.Add(clientcommand);       
  1. 发送信息
 byte[] data = new byte[1024];
 data = Encoding.ASCII.GetBytes(txtClient.Text); 
 clientSocket.Send(data, data.Length, SocketFlags.None);

代码示例:
类 Serv

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

namespace 网络连接池
{
    public class Serv
    {
        public Socket listenfd;
        public Conn[] conns;//新建连接池数组
        public int maxConn = 50;//最大连接数

        public int NewIndex()
        {
            if (conns == null)
                return -1;//连接池数组为空时,返回负1
            for (int i = 0; i < conns.Length ; i++)
            {
                if (conns[i] == null)
                {
                    conns[i] = new Conn();//连接池数组当前位置为空时,新建一个连接池对象
                    return i;//返回值为conns数组的index
                }
                else if (conns[i].isUse == false)
                {
                    return i;//如果当前连接池位置没有被使用时,且不为空时,返回conns数组的index
                }
            }
            return -1;
        }

        public void Start(string host, int port)
        {
            conns = new Conn[maxConn];//新建连接池数组,最大连接数为maxConn
            for (int i = 0; i < maxConn; i++)
            {
                conns[i] = new Conn();
            }//新建50个连接池
            listenfd = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ipAdr = IPAddress.Parse(host);
            IPEndPoint ipEp = new IPEndPoint(ipAdr, port);
            listenfd.Bind(ipEp);
            listenfd.Listen(maxConn);
            listenfd.BeginAccept(AcceptCb, null);
            Console.WriteLine("服务器启动成功");
        }

        private void AcceptCb(IAsyncResult ar)
        {
            try
            {
                Socket socket = listenfd.EndAccept(ar);
                int index = NewIndex();
                if (index < 0)
                {
                    socket.Close();
                    Console.Write("警告链接已满");
                }
                else
                {
                    Conn conn = conns[index];
                    conn.Init(socket);
                    string adr = conn.GetAdress();
                    Console.WriteLine("客户端链接[" + adr + "]conn池ID:" + index);
                    conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None, ReceiveCb, conn);
                }
                listenfd.BeginAccept(AcceptCb, null);
            }
            catch (Exception e)
            {
                Console.WriteLine("AcceptCb失败:" + e.Message);
            }
        }

        private void ReceiveCb(IAsyncResult ar)
        {
            Conn conn = (Conn) ar.AsyncState;
            try
            {
                int count = conn.socket.EndReceive(ar);
                if (count <= 0)
                {
                    Console.WriteLine("收到[" + conn.GetAdress() + "]断开链接");
                    conn.Close();
                    return;
                }
                string str = System.Text.Encoding.UTF8.GetString(conn.readBuff, 0, count);
                Console.WriteLine("收到[" + conn.GetAdress() + "]数据:" + str);
                str = conn.GetAdress() + ":" + str;
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str);

                for (int i = 0; i < conns.Length; i++)
                {
                    if (conns[i] == null)
                        continue;
                    if (!conns[i].isUse)
                        continue;
                    Console.WriteLine("将消息传播给" + conns[i].GetAdress());
                    conns[i].socket.Send(bytes);
                }
                conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None, ReceiveCb,
                    conn);
            }
            catch (Exception e)
            {
                Console.WriteLine("收到["+conn.GetAdress() +"]断开链接");
                conn.Close();
            }
        }

    }
   
}

Conn类

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

namespace 网络连接池
{
    public class Conn
    {
        public const int BUFFER_SIZE = 1024;
        public Socket socket;
        public bool isUse = false;
        public byte[] readBuff ;
        public int buffCount = 0;

        public Conn()
        {
            readBuff = new byte[BUFFER_SIZE];
        }
        /// 
        /// 初始化socket
        /// 
        /// 
        public void Init(Socket socket)
        {
            this.socket = socket;
            isUse = true;
            buffCount = 0;
        }

        public int BuffRemain()
        {
            return BUFFER_SIZE - buffCount;
        }
        /// 
        /// 获取连接点的IP地址
        /// 
        /// 
        public string GetAdress()
        {
            if (!isUse)
                return "无法获取地址";
            return socket.RemoteEndPoint.ToString();
        }
        /// 
        /// 断开链接
        /// 
        public void Close()
        {
            if (!isUse)
                return;
            Console.WriteLine("[断开链接]"+GetAdress());
            socket.Close();
            isUse = false;
        }
    }
}

Main方法

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

namespace 网络连接池
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Serv serv = new Serv();
            serv.Start("127.0.0.1",1234);

            while (true)
            {
                string str = Console.ReadLine();
                switch (str)
                {
                    case"quit":
                        return;
                }
            }
        }
    }
}

异步客户端脚本示例

using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Mime;
using System.Net.Sockets;
using UnityEngine.UI;

public class netAsyn : MonoBehaviour
{
    //服务器IP和端口
    public InputField hostInput;
    public InputField portInput;
    //显示客户端收到的消息
    public MediaTypeNames.Text recvText;
    public string recvStr;
    //显示客户端IP和端口
    public MediaTypeNames.Text clientText;
    //聊天输入框
    public InputField textInput;
    //Socket和接收缓冲区
    Socket socket;
    const int BUFFER_SIZE = 1024;
    public byte[] readBuff = new byte[BUFFER_SIZE];

    //因为只有主线程能够修改UI组件属性
    //因此在Update里更换文本
    void Update()
    {
        recvText.text = recvStr;
    }

    //连接
    public void Connetion()
    {
        //清理text
        recvText.text = "";
        //Socket
        socket = new Socket(AddressFamily.InterNetwork,
                         SocketType.Stream, ProtocolType.Tcp);
        //Connect
        string host = hostInput.text;
        int port = int.Parse(portInput.text);
        socket.Connect(host, port);
        clientText.text = "客户端地址 " + socket.LocalEndPoint.ToString();
        //Recv
        socket.BeginReceive(readBuff, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCb, null);
    }

    //接收回调
    private void ReceiveCb(IAsyncResult ar)
    {
        try
        {
            //count是接收数据的大小
            int count = socket.EndReceive(ar);
            //数据处理
            string str = System.Text.Encoding.UTF8.GetString(readBuff, 0, count);
            if (recvStr.Length > 300) recvStr = "";
            recvStr += str + "\n";
            //继续接收  
            socket.BeginReceive(readBuff, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCb, null);
        }
        catch (Exception e)
        {
            recvText.text += "链接已断开";
            socket.Close();
        }
    }

    //发送数据
    public void Send()
    {
        string str = textInput.text;
        byte[] bytes = System.Text.Encoding.Default.GetBytes(str);
        try
        {
            socket.Send(bytes);
        }
        catch { }
    }
}

你可能感兴趣的:(C#——Socket编程)