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(); }}
新闻热点
疑难解答