using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class unityClient : MonoBehaviour {
private Socket socket;
public InputField input;
private byte[] date = new byte[1024];
private Thread t;
private string message;
public Text text;
// Use this for initialization
void Start () {
ConnectToServer();
}
void Update()
{
if (message != null&&message != "")
{
text.text += message+"\n";
message = "";
}
}
void ConnectToServer()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse("192.168.2.100");
IPEndPoint point = new IPEndPoint(ip, 7788);
socket.Connect(point);
t = new Thread(ReciveReceiveMessage);
t.Start();
}
void ReciveReceiveMessage()
{
while (true)
{
if (socket.Connected == false)
break;
int count = socket.Receive(date);
message = Encoding.UTF8.GetString(date, 0, count);
}
}
void SendMessage(string message)
{
byte[] date = Encoding.UTF8.GetBytes(message);
socket.Send(date);
}
public void OnSendBtn()
{
string str = input.text;
SendMessage(str);
input.text = "";
}
void OnDestroy()
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
}
unity客户端
最新推荐文章于 2025-07-07 10:57:25 发布
本文介绍了一个使用C#在Unity环境中实现的TCP客户端程序,该程序能够连接到指定的服务器地址并进行消息发送与接收。客户端包括输入字段用于消息输入、文本显示区域展示接收的消息、以及按钮触发消息发送。
2万+

被折叠的 条评论
为什么被折叠?



