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

 Golang服务器,Unity客户端 通信_第1张图片

这个是需要手动配置的!

 

 

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

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

服务器执行结果

Golang服务器,Unity客户端 通信_第2张图片

Unity客户端执行结果

Golang服务器,Unity客户端 通信_第3张图片

 

程序代码:

//----------------------------------- 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

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

Golang服务器,Unity客户端 通信_第4张图片

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);
    }
}


 

你可能感兴趣的:(Unity客户端,Golang服务器)