執行解果:
Golang, Go 語言 伺服器:
Unity 客戶端執行結果:
程式碼:
//----------------------------------- Unity C# 客戶端 using UnityEngine; using System.Collections; using System; using System.Net; using System.Net.Sockets; using System.IO; using System.Threading; public class NewBehaviourScript : MonoBehaviour { string ip = "127.0.0.1"; // 請改為自己對外的 IP 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() }
全站熱搜
留言列表