Golang服务器,Unity客户端 通信

前端之家收集整理的这篇文章主要介绍了Golang服务器,Unity客户端 通信前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

2016.6.10 孙广东

http://golangtc.com/download

编辑器有:

1 liteIDE

2、Sublime Text 2

3、Google Go language IDE built using the IntelliJ Platform

这个是需要手动配置的!

下面就介绍三种 通信的例子:

一、Unity 客戶端與 Golang 伺服器做通信

服务器执行结果

Unity客户端执行结果

程序代码

//----------------------------------- Unity C# 客戶端

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

public class Server1 : MonoBehavIoUr
{
    readonly string _ip = "127.0.0.1"; // 改为自己对外的 IP
    readonly int _port = 1024;

    void OnGUI()
    {
        if (GUI.Button(new Rect(10,10,100,100),"Send Public IP"))
        {
            Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            socket.Connect(_ip,_port);
            NetworkStream stream = new NetworkStream(socket);
            StreamWriter sw = new StreamWriter(stream);
            StreamReader sr = new StreamReader(stream);

            sw.WriteLine("你好服务器,我是客户端。");
            sw.Flush();

            string st = sr.ReadLine();
            print(st);

            sw.Close();
            stream.Close();
            socket.Close();
        }
    }
}


//-------------------------------------- Golang,Go語言 伺服器

package main

import (
"bufio"
"net"
)

func main() {

listener,_ := net.Listen("tcp",":1024")
println("启动服务器...")

for {
conn,_ := listener.Accept() // 持续监听客户端连接
go ClientLogic(conn)
}
}

func ClientLogic(conn net.Conn) {

// 从客户端接受数据
s,_ := bufio.NewReader(conn).ReadString('\n')
println("由客户端发来的消息:",s)

// 发送消息给客户端
conn.Write([]byte("东东你好\n"))

// 关闭连接
conn.Close()
}


二、上传图片给服务器(后端)Server 使用 Golang

运行结果 就是把内容 添加到了这里!

using UnityEngine;
using System.Collections;

public class Server2 : MonoBehavIoUr
{
    // 编辑器赋值,图片要设置为 Advanced 并且选中 可读可写 (否则会失败)
    public Texture2D t; 

    IEnumerator Start()
    {
        WWWForm wwwF = new WWWForm();
        wwwF.AddBinaryData("file",t.EncodeToPNG(),"A.png");
        WWW www = new WWW("http://127.0.0.1:8080/upload",wwwF);
        yield return www;
        print("Upload Finish !!");
    }
}


// 以下為 Golang Web 伺服器
package main
import (
"io/IoUtil"
"net/http"
"os"
)
func uploadHandle(w http.ResponseWriter,r *http.Request) {

file,head,_ := r.FormFile("file")
defer file.Close()
bytes,_ := IoUtil.ReadAll(file)
IoUtil.WriteFile(head.Filename,bytes,os.ModeAppend)
}
func main() {
http.HandleFunc("/upload",uploadHandle)
http.ListenAndServe(":8080",nil)
}


三、传参数给 Golang Web 服务器,并回传讯息给 Unity

执行结果:

Golang Server  code

package main
import (
"fmt"
"net/http"
)

func loadin(w http.ResponseWriter,r *http.Request) {
username := r.FormValue("username")
password := r.FormValue("password")
fmt.Fprintf(w,"<html><body>")
fmt.Fprintf(w,"Hello,%s ! <br/>",username)
fmt.Fprintf(w,"Your password is : %s!",password)
fmt.Fprintf(w,"</body></html>")
}

func main() {
http.HandleFunc("/loadin",loadin)
http.ListenAndServe(":8080",nil)
}


Unity C# code

using UnityEngine;
using System.Collections;

public class Server3 : MonoBehavIoUr
{

    IEnumerator Start()
    {
        WWWForm wwwF = new WWWForm();
        wwwF.AddField("username","Loli");
        wwwF.AddField("password","Kitty");
        WWW www = new WWW("http://127.0.0.1:8080/loadin",wwwF);
        yield return www;
        print(www.text);
    }
}
原文链接:https://www.f2er.com/go/189672.html

猜你在找的Go相关文章