unity使用TCP与服务器对接

服务端代码(控制台,接收消息):

using System;
using System.Net;
using System.Net.Sockets;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
          
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //初始化一个SOCKET
            IPEndPoint ip = new IPEndPoint(IPAddress.Parse("192.168.1.104"),9900);
            //初始化一个ipendpoint
            server.Bind(ip);//绑定到server上
            server.Listen(0);//客户端个数
            Socket client = server.Accept();
            //建立一个链接
            Console.WriteLine("接受了一个链接");
            byte[] data = new byte[1024];
            //接受消息
            Console.WriteLine("data=" + data);
            int count = client.Receive(data);
            //count是client链接接受到的内容
            string msg = System.Text.Encoding.UTF8.GetString(data, 0, count);
            //转换data为能看的消息
            Console.WriteLine("接受>>" + msg);
            Console.ReadKey();
            client.Close();
            server.Close();
        }
    }
}

客户端(发送消息,unity):


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

public class Socketer : MonoBehaviour
{
    private void Start()
    {
        Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
       // TcpClient client = new TcpClient();//初始化一个链接
        try
        {
            clientSocket.Connect("192.168.1.104", 9900);//使用指定的IP和端口链接到目标监听器
        }
        catch (Exception ex)
        {
            Debug.Log("客户端连接异常:" + ex.Message);
        }
        Debug.Log("链接已经建立");
        clientSocket.Send(Encoding.UTF8.GetBytes("Hello!sss"));
        
    }
}

实现效果:

unity使用TCP与服务器对接_第1张图片

 参考资料:

(23条消息) C#Tcp服务端与客户端接收消息与发送消息_piyixia的博客-CSDN博客_c#客户端接受服务器消息

你可能感兴趣的:(UNITY学习之路,unity,tcp/ip,服务器)