サーバー
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Net.NetworkInformation;
using UnityEngine.UI;
public class Server_start : MonoBehaviour
{ //配置相关
private string _ip = "";
private int _port = 10000;
//服务器套接字
private Socket _server;
//接收客户端连接的线程,因为Accept是一个阻塞现成的方法,而且此方法还需要循环执行
private Thread _acceptServerClientThread;
//所有已经连接的客户端
private List<Socket> _clientList = new List<Socket>();
public Text Phow_ip_txt;
public GameObject Prefabs;
public Transform Parent;
private bool stop;
// Start is called before the first frame update
void Start()
{
IPAddress iPAddress = GetTpv4(NetworkInterfaceType.Ethernet);
_ip = iPAddress.ToString();
Phow_ip_txt.text = string.Format("Ip:{0}", _ip);
ServerSetUp();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
SendALL("Sever:连接成功");
}
}
//启动服务器=建立流式套接字+配置本地地址
public void ServerSetUp()
{
try
{
//建立套接字,
_server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//配置本地地址
EndPoint endpooint = new IPEndPoint(IPAddress.Parse(_ip), _port);
_server.Bind(endpooint);
//监听和接受客户端请求
_server.Listen(30);
//开启一个接受连接的线程
_acceptServerClientThread = new Thread(AcceptClientConnect);
_acceptServerClientThread.Start();
Console.WriteLine("{0}:{1} ServerSetUp...", _ip, _port);
GameObject message = GameObject.Instantiate(Prefabs, Parent);
message.transform.GetChild(0).GetComponent<Text>().text = "服务器已开启!";
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
//接受客户端连接
public void AcceptClientConnect()
{
while (true)
{
try
{
//接受客户端连接
Socket clientSocket = _server.Accept();
//维护一个客户端在线列表
_clientList.Add(clientSocket);
//获取客户端的网络标识
IPEndPoint clientEndPoint = clientSocket.RemoteEndPoint as IPEndPoint;
//输出一下地址和端口
Console.WriteLine("{0}:{1} Connect....", clientEndPoint.Address.ToString(), clientEndPoint.Port);
//接受客户端消息的线程
Thread acceptClientMsg = new Thread(AcceptMsg);
acceptClientMsg.Start(clientSocket);
Send("连接成功", clientSocket);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
if (stop == true)
{
break;
}
}
Close();
}
//接收消息
public void AcceptMsg(object obj)
{
//强转为Socket类型
Socket client = obj as Socket;
//字节数组 接受传来的的信息 1024*64
byte[] buffer = new byte[client.ReceiveBufferSize];
//获取客户端的网络地址标识
IPEndPoint clientEndPoint = client.RemoteEndPoint as IPEndPoint;
try
{
while (true)
{
//接收消息存储
int len = client.Receive(buffer);
string str = Encoding.UTF8.GetString(buffer, 0, len);
GameObject message = GameObject.Instantiate(Prefabs, Parent);
Console.WriteLine("{0}:{1}:{2}", clientEndPoint.Address, _port, str);
message.transform.GetChild(0).GetComponent<Text>().text =
string.Format("Ip:{0}\nPort:{1}\nMessage:{2}", clientEndPoint.Address, _port, str);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
_clientList.Remove(client);
}
}
//给某个客户端发消息
public void Send(string str, Socket client)
{
try
{
//string=>byte[]
byte[] strBytes = Encoding.UTF8.GetBytes(str);
client.Send(strBytes);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
//发给所有人
public void SendALL(string str)
{
for (int i = 0; i < _clientList.Count; i++)
{
Send(str, _clientList[i]);
}
}
//获取IP地址
public IPAddress GetTpv4(NetworkInterfaceType type)
{
NetworkInterface[] networkinterface = NetworkInterface.GetAllNetworkInterfaces();
for (int i = 0; i < networkinterface.Length; i++)
{
Console.WriteLine(networkinterface[i].Name + "------" + networkinterface[i].ToString());
//无线网操作
if (type == networkinterface[i].NetworkInterfaceType && networkinterface[i].OperationalStatus == OperationalStatus.Up)
{
UnicastIPAddressInformationCollection ips = networkinterface[i].GetIPProperties().UnicastAddresses;
foreach (UnicastIPAddressInformation item in ips)
{
if (item.Address.AddressFamily == AddressFamily.InterNetwork)
{
return item.Address;
}
}
}
}
return null;
}
//关闭套接字
public void Close()
{
if (_clientList.Count > 0)
{
for (int i = 0; i < _clientList.Count; i++)
{
_clientList[i].Close();
}
_clientList.Clear();
_server.Close();
_acceptServerClientThread.Abort();
}
}
private void OnDestroy()
{
Close();
}
private void OnApplicationQuit()
{
Close();
}
}
クライアント
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Collections;
public class Client_start : MonoBehaviour
{
public Button Link;
public InputField InputField_Ip;
public InputField InputField_Port;
public GameObject Send_Mesage_Panle;
public GameObject Prefabs;
public Transform Parent;
private void Start()
{
Send_Mesage_Panle.transform.GetChild(1).GetComponent<Button>().onClick.AddListener(delegate ()
{
Send(Send_Mesage_Panle.transform.GetChild(0).GetComponent<InputField>().text);
});
StartCoroutine(Load_Ip());
}
IEnumerator Load_Ip()
{
string url = Application.streamingAssetsPath+ "/Url.txt";
UnityWebRequest unityWebRequest = UnityWebRequest.Get(url);
yield return unityWebRequest.SendWebRequest();
if (unityWebRequest.isNetworkError || unityWebRequest.isHttpError)
{
Debug.Log(unityWebRequest.error);
}
else
{
print(unityWebRequest.downloadHandler.text);
string[] str = unityWebRequest.downloadHandler.text.Split('\n');
InputField_Ip.text = str[0];
InputField_Port.text= str[1];
Link.onClick.AddListener(delegate ()
{
ClientConnect(IPAddress.Parse(InputField_Ip.text), int.Parse(InputField_Port.text));
});
}
}
private Socket clientsocket;
private Thread _acceptServerMsg;
private bool stop;
public void ClientConnect(IPAddress ip,int port)
{
try
{
clientsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientsocket.Connect(ip, port);
//接受消息的 线程
_acceptServerMsg = new Thread(AcceptServerMsg);
_acceptServerMsg.Start();
}
catch (Exception e)
{
print(e.Message);
}
}
public void AcceptServerMsg()
{
byte[] buffer = new byte[1024 * 64];
while (true)
{
try
{
int len = clientsocket.Receive(buffer);
string str = Encoding.UTF8.GetString(buffer, 0, len);
print(string.Format("Reveice Msg From Server:{0}", str));
if (str == "连接成功")
{
Link.transform.parent.gameObject.SetActive(false);
Send_Mesage_Panle.gameObject.SetActive(true);
}
GameObject message = GameObject.Instantiate(Prefabs, Parent);
message.transform.GetChild(0).GetComponent<Text>().text = "Sever:" + str;
}
catch (Exception e)
{
print(e.Message);
}
if (stop == true)
{
break;
}
}
Close();
}
//发送消息
public void Send(string str)
{
try
{
//string=>byte[]
byte[] strBytes = Encoding.UTF8.GetBytes(str);
clientsocket.Send(strBytes);
GameObject message = GameObject.Instantiate(Prefabs, Parent);
message.transform.GetChild(0).GetComponent<Text>().text ="Client:"+ str;
}
catch (Exception e)
{
print(e.Message);
}
}
//关闭套接字
public void Close()
{
if (clientsocket.Connected)
{
clientsocket.Close();
}
_acceptServerMsg.Abort();
}
private void OnDestroy()
{
Close();
}
private void OnApplicationQuit()
{
Close();
}
}