首页 > 编程语言 > 详细

unity3d实现Socket

时间:2015-11-16 22:32:35      阅读:361      评论:0      收藏:0      [点我收藏+]

首先创建一个服务器

using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System.Threading; //引入线程的包

public class ServerSocket : MonoBehaviour 
{
    private Socket serverSocket;
    void Start()
    {
        //1使用socket创建一个对象
        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
        //2创建一个IpEndPoint对象(加入Ip地址)
        IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2333);
        serverSocket.Bind(endPoint);
        serverSocket.Listen(10); //3设置缓冲区的大小, 进行监听

        ThreadStart s = new ThreadStart(X);  //创建一个线程
        Thread t = new Thread(s);
        t.Start();
    }
    void Update ()
    {
    }

    private void X()
    {
        //4使用Accept()方法
        Socket clientSocket = serverSocket.Accept();
        //5接收使用Receive()方法接受客户端消息
        byte[] receiveBuffer = new byte[1024]; //缓存的大小
        int count = clientSocket.Receive(receiveBuffer);
        string receiveStr = System.Text.Encoding.UTF8.GetString(receiveBuffer); //把byte转化为字符串
        print(receiveStr);

        //6发送数据
        string str = "老王你好";
        byte[] sendBuffer = new byte[1024];
        sendBuffer = System.Text.Encoding.UTF8.GetBytes(str);
        clientSocket.Send(sendBuffer);
        clientSocket.Close();
    }

}


在家建立一个客户端

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


public class ClientSocket : MonoBehaviour 
{
    private Socket clientSocket;
    void Start ()
    {
    }
    void Update ()
    {
        if(Input.GetKeyDown(KeyCode.P)) //按下P键,连接服务器
        {       //1.创建客户端(Socket)
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //    2.    使用 Connect() 方法连接服务器
            clientSocket.Connect("127.0.0.1", 2333);

            string str = "你好, 我是老王!";
            byte[] sendBuffer = System.Text.Encoding.UTF8.GetBytes(str);
            //    3.    使用 Send() 方法向客户端发送消息
            clientSocket.Send(sendBuffer);

            ThreadStart s = new ThreadStart(X);
            Thread t = new Thread(s);
            t.Start();
           
        }
    }

    private void X()
    {
        byte[] receiveBuffer = new byte[1024];
        //    4.    使用 Receive() 方法接收客户端消息
        clientSocket.Receive(receiveBuffer);
        string receiveStr = System.Text.Encoding.UTF8.GetString(receiveBuffer);
        print(receiveStr);

        //    5.    使用 Close() 方法断开连接
        clientSocket.Close();
    }
}

 

 

 

unity3d实现Socket

原文:http://www.cnblogs.com/ZhiXing-Blogs/p/4970109.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!