上一章写了写socket的服务端,今天来看下客户端的东西,总之是大同小异
客户端主要流程如上图client,大致步骤为
创建socket,用来连接服务端
使用connnect连接指定服务器
使用send向服务端发送消息
使用receive来接收服务端的信息
完整代码如下:
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Net;
using System;
public class StateClient
{
public Socket _myClient;
public const int _bufferSize = 1024 ;
public byte[] _buffer = new byte[_bufferSize];
public StringBuilder _sb = new StringBuilder();
}
public struct SIpEndPoint
{
public string _ip;
public int _port;
}
public class TcpClient
{
private static TcpClient _tcpClient;
public static SIpEndPoint _sIpEndPoint;
private Socket _client;
private string _data;
public bool _connectSuccess;
public static TcpClient GetInstance()
{
if(_tcpClient == null)
{
_tcpClient = new TcpClient();
}
return _tcpClient;
}
public TcpClient()
{
_client = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPAddress _ipAddress = IPAddress.Parse(_sIpEndPoint._ip);
IPEndPoint _ipEndPoint = new IPEndPoint(_ipAddress,_sIpEndPoint._port);
IAsyncResult _result = _client.BeginConnect(_ipEndPoint,new AsyncCallback(ConnectCallBack),_client);
_connectSuccess = _result.AsyncWaitHandle.WaitOne(500,true);
if(_connectSuccess)
{
StateClient _state = new StateClient();
_state._myClient = _client;
_client.BeginReceive(_state._buffer,0,StateClient._bufferSize,SocketFlags.None,new AsyncCallback(ReceiveCallBack),_state);
}
else
{
close();
}
}
void ConnectCallBack(IAsyncResult _ar)
{
Debug.Log("请求连接成功");
}
void ReceiveCallBack(IAsyncResult _ar)
{
StateClient _state = (StateClient)_ar.AsyncState;
Socket _handlerEnd = _state._myClient;
int ReceiverLength= _handlerEnd.EndReceive(_ar);
if(ReceiverLength >0)
{
//_state._sb.Append(Encoding.ASCII.GetString(_state._buffer,0,ReceiverLength));//字符串叠加
string _receiveData = Encoding.ASCII.GetString(_state._buffer,0,ReceiverLength);
ServeReciveData(_receiveData);
}
_handlerEnd.BeginReceive(_state._buffer,0,StateClient._bufferSize,SocketFlags.None,new AsyncCallback(ReceiveCallBack),_state);
}
void ServeReciveData(string _str)
{
_data = _str;
Debug.Log(_data);
}
public void SendMessage(string _data)
{
try
{
if(!_client.Connected)
{
_client.Close();
return;
}
byte[] _sendData = Encoding.ASCII.GetBytes(_data);
IAsyncResult _result = _client.BeginSend(_sendData,0,_sendData.Length,SocketFlags.None,new AsyncCallback(SendCallBack),_client);
bool _isSendSuccess = _result.AsyncWaitHandle.WaitOne(5000,true);
if(!_isSendSuccess)
{
Debug.Log("发送数据失败");
}
}
catch(Exception e)
{
Debug.Log("error:" +e);
}
}
void SendCallBack(IAsyncResult _ar)
{
}
void close()
{
if(_client != null && _client.Connected)
{
_client.Shutdown(SocketShutdown.Both);
_client.Close();
}
_client = null;
}
public string RetunrData()
{
return _data;
}
}
调用代码如下:
using UnityEngine;
using System.Collections;
public class TcpClientTest : MonoBehaviour {
TcpClient _tcpClient;
void Start ()
{
TcpClient._sIpEndPoint._ip = "192.168.1.216";
TcpClient._sIpEndPoint._port = 159;
_tcpClient = TcpClient.GetInstance();
}
void Update ()
{
if(Input.GetMouseButtonDown(0))
{
_tcpClient.SendMessage("licaoguan");
}
}
}