Golang服务端:
package main
import (
"fmt"
"log"
"math/rand"
"net"
"os"
"strconv"
)
func main() {
//建立socket,监听端口 第一步:绑定端口
//netListen, err := net.Listen("tcp", "localhost:1024")
netListen, err := net.Listen("tcp", "192.168.26.142:9800")
CheckError(err)
//defer延迟关闭改资源,以免引起内存泄漏
defer netListen.Close()
Log("Waiting for clients")
for {
conn, err := netListen.Accept() //第二步:获取连接
if err != nil {
continue //出错退出当前一次循环
}
Log(conn.RemoteAddr().String(), " tcp connect success")
//handleConnection(conn) //正常连接就处理
//这句代码的前面加上一个 go,就可以让服务器并发处理不同的Client发来的请求
go handleConnection(conn) //使用goroutine来处理用户的请求
}
}
//处理连接
func handleConnection(conn net.Conn) {
//关闭连接
defer conn.Close()
buffer := make([]byte, 2048)
n, err := conn.Read(buffer) //第三步:读取从该端口传来的内容
//words := "ok" //向链接中写数据,向链接既可以先读也可以先写,看自己的需要
words := "golang socket server : " + strconv.Itoa(rand.Intn(100)) //向链接中写数据
conn.Write([]byte(words))
if err != nil {
Log(conn.RemoteAddr().String(), " connection error: ", err)
return //出错后返回
}
Log(conn.RemoteAddr().String(), "receive data string:\n", string(buffer[:n]))
}
//log输出
func Log(v ...interface{}) {
log.Println(v...)
}
//处理error
func CheckError(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
os.Exit(1)
}
}
Unity客户端:
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
public class SocketTest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
ClientTest();
}
// Update is called once per frame
void Update()
{
}
void ClientTest() {
// 1. 创建Socket实例
Socket client_socket = new Socket(AddressFamily.InterNetwork, // 局域网
SocketType.Stream, // 类型:流套接字
ProtocolType.Tcp); // 协议类型:TCP
// 2. 指定服务器端IP地址, 字符串转换为IP地址类
// !! 要引入命名空间 System.Net
IPAddress ipAddr = IPAddress.Parse("192.168.26.142"); //指定并转换
// 3. 创建IP实体类对象 IP地址+端口号
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 9800);
// 4. 连接服务器端
client_socket.Connect(ipEndPoint);
// 5. 发送数据
// 5.1 编辑要发送的数据流
string msg = "你好,Unity! \r\n";
// !! 要引入命名空间 System.Text
byte[] data = Encoding.UTF8.GetBytes(msg);
// 5.2 发送
client_socket.Send(data);
}
}
启动效果: