C#-Socket

包含成员变量:

地址IP;端口;协议UDP/TCP

一、UDP协议下的socket通信:

1、创建Socket对象

2、发送Send/接收Receive

3、接收Receive/发送Send

4、释放资源Close

发送信息的示例

1)客户端(发送端)示例

using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
public class ChatUDPClient : MonoBehaviour
{
    private string IpAddress = "";//Ip地址
    private int port;//端口
    private ChatUDPServer server; 
    private UdpClient udpService;
    private IPEndPoint serverEP;
    private void Start()//创建Socket对象
    {
        server =GetComponent<ChatUDPServer>();
        //基于UDP协议的网络服务
        //终结点(地址与端口)
        IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(IpAddress), port);
        udpService = new UdpClient(localEP);

        //构建服务端终结点(供发送时使用)
        serverEP = new IPEndPoint(IPAddress.Parse(server.ReceiveIpAddress), server.receivePort);
    }
    //发送消息
    public void SendChatMessage(string message)
    {
        //Byte[](01数字)
        byte[] dgram = Encoding.UTF8.GetBytes(message);
        udpService.Send(dgram,dgram.Length,serverEP);
    }
    //释放资源(不释放会卡死)
    private void OnApplicationQuit()
    {
        udpService.Close();
    }
}

2)服务端(接收端)示例

using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;

public class ChatUDPServer : MonoBehaviour
{
    public string ReceiveIpAddress = "";
    public int receivePort;
    private UdpClient udpService;
    private Thread threadReceive;
    private void Start()
    {
        IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ReceiveIpAddress), receivePort);
        udpService = new UdpClient(ep);
        //防止主线程被阻塞
        threadReceive = new Thread(ReceiveChatMessage);
        threadReceive.Start();
    }
    private void ReceiveChatMessage()
    {
        while (true)
        {
            //任意地址、任意端口
            IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
            //接收消息Receive
            //收到消息前,参数表示需要监听的终结点
            //收到消息后,参数表示实际收到消息的终结点
            //收到消息前,阻塞线程,
            //收到消息后,继续执行
            //返回值就是收到的消息
            byte[] data = udpService.Receive(ref remote);
            //解码
            string str = Encoding.UTF8.GetString(data);
        }
    }
    private void OnApplicationQuit()
    {
        threadReceive.Abort();
        udpService.Close();
    }
}

二、TCP协议下的通信

1)客户端示例(发送端)

using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;

public class ChatTCPClient : MonoBehaviour
{
    public string ip;
    public int port;
    private TcpClient tcpService;
    private ChatTCPServer server;
    //创建Socket对象
    private void Start()
    {
        server = GetComponent<ChatTCPServer>();
        IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(ip), port);
        tcpService = new TcpClient(localEP);
        //创建链接
        IPEndPoint serverEP = new IPEndPoint(IPAddress.Parse(server.receiveIp),server.receivePort);
        tcpService.Connect(serverEP);
    }
    //发送消息
    public void SendChatMessage(string msg)
    {
        byte[] buffer = Encoding.Unicode.GetBytes(msg);
        //获取网络流
        NetworkStream stream = tcpService.GetStream();
        stream.Write(buffer, 0, buffer.Length);
    }
    //释放资源
    private void OnApplicationQuit()
    {
        //问题:客户端绑定端口后,短时间内(30s--4min)内再次链接,提示端口占用
        //解决:客户端每次更换端口
                        //服务端先断开链接
        //下线通知,让服务端先断开
        SendChatMessage("Quit");
        Thread.Sleep(500);
        tcpService.Close();
    }
}

2)服务端示例(接收端)

using System.Net.Sockets;
using System.Net;
using System.Text;
using UnityEngine;
using System.Threading;

public class ChatTCPServer : MonoBehaviour
{
    public string receiveIp;
    public int receivePort;
    private TcpListener tcpListener;
    private Thread threadListener;
    //创建监听器(Socket对象)
    private void Start()
    {
        IPEndPoint localEP = new IPEndPoint(IPAddress.Parse(receiveIp), receivePort);
        tcpListener = new TcpListener(localEP);
        //开启监听器
        tcpListener.Start();
        threadListener = new Thread(ReceiveChatMessage);
        threadListener.Start();
    }
    //接收消息
    public void ReceiveChatMessage()
    {
        //接收客户端
        //如果没有监听到客户端链接,则阻塞线程
        //如果监听到链接,则继续执行
        TcpClient client = tcpListener.AcceptTcpClient();
        using (NetworkStream stream = client.GetStream())
        {
            byte[] buffer = new byte[1024];
            int count;
            while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)//返回实际读取到的字节数,如果为0,则表示客户端下线
            {
                //如果没有读取到数据则阻塞线程
                //如果读取到数据,则继续
                //如果需要监听多个客户端链接,则需要开启线程
                string msg = Encoding.Unicode.GetString(buffer, 0, count);
                if(msg == "Quit")
                {
                    break;
                }
            }
        }
    }
    //释放资源
    private void OnApplicationQuit()
    {
        tcpListener.Stop();
        //可有可无
       threadListener.Abort();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值