Server:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
public class Server : MonoBehaviour
{
#region TCP
private Socket _serverSocket;
private bool _isRunThread = true;
private List<SocketState> _socketStates;
private void Start()
{
Init();
}
private void Update()
{
if (_socketStates.Count > 0)
{
foreach (SocketState state in _socketStates)
{
state.BeginReceive();
}
}
}
private void Init()
{
_socketStates = new List<SocketState>();
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 18010);
_serverSocket = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
_serverSocket.Bind(ipEndPoint);
_serverSocket.Listen(10);
Thread thread = new Thread(ListenRecv);
thread.Start();
}
/// <summary>
/// 接收数据
/// </summary>
private void ListenRecv()
{
while (_isRunThread)
{
try
{
_serverSocket.BeginAccept(AsyncCallBack, _serverSocket);
}
catch (Exception ex)
{
}
}
Thread.Sleep(1000);
}
/// <summary>
/// 异步得到数据
/// </summary>
/// <param name="ar">返回的数据就是socket</param>
private void AsyncCallBack (IAsyncResult ar)
{
Socket listnSocket = (Socket) ar.AsyncState;
//堵塞式
Socket clientSocket = listnSocket.EndAccept(ar);
_socketStates.Add(new SocketState(clientSocket));
}
#endregion
private void OnDestroy()
{
_serverSocket.Shutdown(SocketShutdown.Both);
_serverSocket.Close();
}
}
/// <summary>
/// 客户端的连接
/// </summary>
public class SocketState
{
private Socket _clientSocket;
private byte[] _bufferBytes;
public SocketState(Socket clientSocket)
{
_clientSocket = clientSocket;
_bufferBytes = new byte[1024];
}
#region BeginReceive
/// <summary>
/// 异步接收数据
/// </summary>
public void BeginReceive()
{
_clientSocket.BeginReceive(_bufferBytes, 0, 1024, SocketFlags.None, BeginReceiveCallback, this);
}
private void BeginReceiveCallback(IAsyncResult ar)
{
int lenth = _clientSocket.EndReceive(ar);
string str = Encoding.Default.GetString(_bufferBytes, 0, lenth);
Debug.Log("server receive ---->" + str);
BeginSend(str);
}
#endregion
#region Send
public void BeginSend(string msg)
{
byte[] buffer = Encoding.Default.GetBytes(msg);
_clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, BeginSendCallback, this);
}
private void BeginSendCallback(IAsyncResult ar)
{
int lenth = _clientSocket.EndSend(ar);
Debug.Log("send lenth --->" + lenth);
}
#endregion
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
public class Client : MonoBehaviour
{
#region TCP
private Socket _clientSocket;
private byte[] _bufferBytes;
private SocketBuffer _socketBuffer;
private void Start()
{
_socketBuffer = new SocketBuffer(6, CallBackRecvOver);
Init();
}
private void CallBackRecvOver(byte[] addData)
{
//接收到整个消息
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
BeginSend("123456789");
}
BeginReceive();
}
private void Init()
{
_bufferBytes = new byte[1024];
IPAddress address = IPAddress.Parse("127.0.0.1");
IPEndPoint point = new IPEndPoint(address, 18010);
_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_clientSocket.BeginConnect(point, BeginConnectCallback, _clientSocket);
}
/// <summary>
/// 开始异步连接
/// </summary>
/// <param name="ar"></param>
private void BeginConnectCallback(IAsyncResult ar)
{
_clientSocket.EndConnect(ar);
Debug.Log("connect server is finish!!!");
}
#region BeginReceive
/// <summary>
/// 异步接收数据
/// </summary>
public void BeginReceive()
{
_clientSocket.BeginReceive(_bufferBytes, 0, 1024, SocketFlags.None, BeginReceiveCallback, this);
}
private void BeginReceiveCallback(IAsyncResult ar)
{
int lenth = _clientSocket.EndReceive(ar);
_socketBuffer.RecvByte(_bufferBytes, lenth);
//string str = Encoding.Default.GetString(_bufferBytes, 0, lenth);
//Debug.Log("收到服务器数据 ---->" + str);
}
#endregion
#region Send
public void BeginSend(string msg)
{
byte[] buffer = Encoding.Default.GetBytes(msg);
_clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, BeginSendCallback, this);
}
private void BeginSendCallback(IAsyncResult ar)
{
int lenth = _clientSocket.EndSend(ar);
Debug.Log("发送到服务器数据 --->" + lenth);
}
#endregion
private void OnDestroy()
{
_clientSocket.Shutdown(SocketShutdown.Both);
_clientSocket.Close();
}
#endregion
}