1、使用Socket的Tcp
服务端:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System;
public class ScocketServer : MonoBehaviour {
private Thread _StartServer;
byte[] byte_receive;
Socket RecieveSocket;
IPEndPoint iep;
EndPoint ep;
// Use this for initialization
void Start () {
//Socket Tcp
byte_receive = new byte[100];
iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1001);
RecieveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
RecieveSocket.Bind(iep);
RecieveSocket.Listen(10);
_StartServer = new Thread(StartServer);
_StartServer.Start();
}
// Update is called once per frame
void Update () {
}
void StartServer()
{
Debug.Log("服务端:等人...");
Socket tempSocket = RecieveSocket.Accept();//阻断
Debug.Log("服务端:有人来了");
while (true)
{
int datalength = tempSocket.Receive(byte_receive);
if (datalength != 0)
{
string msg = Encoding.Unicode.GetString(byte_receive);
Debug.Log("服务端:我收到消息:" + msg);
}
}
}
private void OnApplicationQuit()
{
if (_StartServer != null)//关闭线程
{
_StartServer.Interrupt();
_StartServer.Abort();
}
//最后关闭socket
if (RecieveSocket != null)
RecieveSocket.Close();
}
}
客户端:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System;
using System.Threading;
public class ScocketClient : MonoBehaviour {
private Thread ClientThread;
int MsgIndex;
Socket ClientSocket;
IPEndPoint ep;
string msg;
byte[] byteSendingArray;
// Use this for initialization
void Start () {
ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1001);
byteSendingArray = new byte[100];
MsgIndex = 0;
}
// Update is called once per frame
void Update () {
if(Input.GetKeyDown(KeyCode.Alpha1))
{
SendMsg();
}
}
private voi