Socket通信

 

大家好:

            最近工作上的需要通过Socket进行数据的传输,完成多人协同的功能,原来用的是RTC通信协议,现在用Socket,废话不多说直接硬菜。

客户端的部分 (unity)

using UnityEngine;
using System.Collections;

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

public class SocketClient : MonoBehaviour
{
    public delegate void  ScoketMsgEvent(string msg);
    public static ScoketMsgEvent scoketMsg;
    //端口
    private int port;
    string resMsg;
    Socket client;
  
    //初始化
    void Awake()
    {

    }

    void Start()
    {
        port = 6000;
    }


    //服务器连接
    public void Connection(string ip) {

        client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        client.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
        Thread t = new Thread(new ThreadStart(Receivemsg));
        t.Start();
    }

    //服务器断开
    public void Disconnect() {

        client.Close();

    }

    //发送
    public void SendMsg(string msg)
    {
        client.Send(Encoding.UTF8.GetBytes(msg));

    }
    //接收
    public string ReceiveMsg(){

        scoketMsg(resMsg);
        return resMsg;
    }

    //接收监听
  void Receivemsg()
    {
        while (true)
        {
            byte[] buffer = new byte[1024];
            int length = client.Receive(buffer);
            resMsg = "\n" + Encoding.UTF8.GetString(buffer, 0, length);
            ReceiveMsg(); 
        }

    }
 

   
 
}
using UnityEngine;
using System.Collections;

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

public class SocketClient : MonoBehaviour
{
    public delegate void  ScoketMsgEvent(string msg);
    public static ScoketMsgEvent scoketMsg;
    //端口
    private int port;
    string resMsg;
    Socket client;
  
    //初始化
    void Awake()
    {

    }

    void Start()
    {
        port = 6000;
    }


    //服务器连接
    public void Connection(string ip) {

        client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        client.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
        Thread t = new Thread(new ThreadStart(Receivemsg));
        t.Start();
    }

    //服务器断开
    public void Disconnect() {

        client.Close();

    }

    //发送
    public void SendMsg(string msg)
    {
        client.Send(Encoding.UTF8.GetBytes(msg));

    }
    //接收
    public string ReceiveMsg(){

        scoketMsg(resMsg);
        return resMsg;
    }

    //接收监听
  void Receivemsg()
    {
        while (true)
        {
            byte[] buffer = new byte[1024];
            int length = client.Receive(buffer);
            resMsg = "\n" + Encoding.UTF8.GetString(buffer, 0, length);
            ReceiveMsg(); 
        }

    }
 

   
 
}
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.UI;

public class LoginUIControl : MonoBehaviour {
    //UI
    public Text msgLable;
    public InputField SendMsg;
    public InputField ip;
    public Button sendBtn;
    public Button loginBtn;
    public SocketClient socketClient;
    // Use this for initialization
    void Start () {
        sendBtn.onClick.AddListener(OnSendBtnClick);
        loginBtn.onClick.AddListener(OnLoginBtnClick);

    }

    // Update is called once per frame
    void Update () {

        ReceiveMsg();
    }

    //登录
    void OnLoginBtnClick() {

        socketClient.Connection(ip.text);
    }

    //发送按键
    void OnSendBtnClick()
    {
        socketClient.SendMsg(SendMsg.text);
        
    }
    //
    void ReceiveMsg() {

        msgLable.text = socketClient.ReceiveMsg();
    }





}

这个是Unity的结构,可以用于参考

服务器端的代码

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

namespace ScoketServer
{
    class Program
    {

        static List<Socket> socketList = new List<Socket>();

        static void Main(string[] args)
        {
            const int bufferSize = 8792;//缓存大小,8192字节

            //实例化服务器端Scoket对象
            Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

            IPAddress ip = IPAddress.Parse("192.168.0.49");
            int port = 6000;
            //封装保存IP和端口号
            EndPoint point = new IPEndPoint(ip, port);
            //监听服务器
            server.Bind(point);
            server.Listen(10);
            Console.WriteLine("服务器监听启动,,,,,,");
            server.BeginAccept(new AsyncCallback(AcceptClient), server);


            ConsoleKey key;
            do
            {
                key = Console.ReadKey(true).Key;
            }
            while (key != ConsoleKey.Q);

          

        }


        static void AcceptClient(IAsyncResult ar)
        {
            Socket myserver = ar.AsyncState as Socket;
            Socket client = myserver.EndAccept(ar);//保存异步连接的客户端
            Console.WriteLine("有新客户端连接。。。");
            socketList.Add(client);
            Console.WriteLine("客户ip信息:" + client.RemoteEndPoint); 
            string msg = "系统信息:欢迎回家";
            byte[] data = Encoding.UTF8.GetBytes(msg);
            client.Send(data);//给客户端发送信息
            Thread t = new Thread(ReceiveMsg);
            t.Start(client);

            myserver.BeginAccept(new AsyncCallback(AcceptClient), myserver);

        }

        //接收信息
        static void ReceiveMsg(Object socket)
        {
            Socket mySocket = socket as Socket;
            while (true)
            {
                byte[] buffer = new byte[1024];
                int length = 0;
                try
                {
                    length = mySocket.Receive(buffer);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception:" + e.Message);//显示异常信息
                    IPEndPoint point = mySocket.RemoteEndPoint as IPEndPoint;
                    string ipp = point.Address.ToString();
                    Console.WriteLine(ipp + "退出回话");
                    socketList.Remove(mySocket);
                    sendAllMsg(ipp + "有人退出回话");
                    break;
                }

                string resMsg = Encoding.UTF8.GetString(buffer, 0, length);

                //resMsg = mySocket.RemoteEndPoint.ToString() + ":" + resMsg;
                IPEndPoint po = mySocket.RemoteEndPoint as IPEndPoint;
                string ip = po.Address.ToString();
                resMsg = ip + "|" + resMsg;
                Console.WriteLine(resMsg);
                sendAllMsg(resMsg);



            }

        }



        //群发消息
        static void sendAllMsg(string resMsg)
        {
            //把接收到的消息群发出去
            for (int i = 0; i < socketList.Count; i++)
            {
                socketList[i].Send(Encoding.UTF8.GetBytes(resMsg));
            }
        }
    }
 
}

大家如何在学的可以参考,喜欢的转发关注。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值