golang 与unity socket 通信

2018-10-05  本文已影响0人  phu

1.golang 代码:
////////////////////////////


TIM截图20181005155919.png

package main

import (
"fmt"
"log"
"net"
"sync"
)

func main() {
var waitGroup = new(sync.WaitGroup)
waitGroup.Add(1)
addr := "0.0.0.0:666" //表示监听本地所有ip的8080端口,也可以这样写:addr := ":8080"
listener, err := net.Listen("tcp", addr) //使用协议是tcp,监听的地址是addr
if err != nil {
log.Fatal(err)
}
conn, err := listener.Accept() //用conn接收链接
if err!=nil {
return
}
go func() {
defer listener.Close() //关闭监听的端口
for {
buf := make([]byte, 1024)
ln,err_:=conn.Read(buf)
if err_!=nil {
break
}
fmt.Println(string(buf[:ln]))
if err != nil {
log.Fatal(err)
break
}
conn.Write([]byte("huhao\n")) //通过conn的wirte方法将这些数据返回给客户端。
}
waitGroup.Done()

}()
waitGroup.Wait()

}
////////////////////
2.unity 代码:
![QV@R]UZNQ(MGMP%4~XX9S1O.png](https://img.haomeiwen.com/i5395507/b36b60196d306517.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

自己create 一个sense 然后添加UI组件Text,InputField ,Button 就可以进行测试了

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

public class login : MonoBehaviour
{
public string ipaddress = "127.0.0.1";
public int port = 666;
private Socket clientSocket;
public InputField MessageInput;
public Text MessageText;
private Thread thread;
private byte[] data = new byte[1024];// 数据容器
private string message = "";
public Button btn;

// Use this for initialization
void Start()
{
    ConnectToServer();
    btn.onClick.AddListener(OnSendButtonClick);
    thread = new Thread(ReceiveMessage);
    thread.Start();
}

// Update is called once per frame
void Update()
{
    //只有在主线程才能更新UI     
    if (message != "" && message != null)
    {
        MessageText.text += "\n" + message;
        message = "";
    }
}

/**     
 *连接服务器端函数   
 **/
void ConnectToServer()
{
    clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);        //跟服务器连接     
    clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ipaddress), port));        //客户端开启线程接收数据        thread = new Thread(ReceiveMessage);        thread.Start();    }
}

void ReceiveMessage()
{
    while (true)
    {
        if (clientSocket.Connected == false)
        { break; }
        int length = clientSocket.Receive(data);
        message = Encoding.UTF8.GetString(data, 0, length);
        print(message);
    }
}
new void SendMessage(string message)
{
    byte[] data = Encoding.UTF8.GetBytes(message);
    clientSocket.Send(data);
}
public void OnSendButtonClick()
{
    string value = MessageInput.text;
    SendMessage(value);
    MessageInput.text = " ";
}  
/**    
 * * unity自带方法  
 * * 停止运行时会执行   
 * * */
void OnDestroy()
{        
    //关闭连接,分接收功能和发送功能,both为两者均关闭     
    clientSocket.Shutdown(SocketShutdown.Both);
    clientSocket.Close();
}

}

上一篇下一篇

猜你喜欢

热点阅读