Socket(Tcp)通信客户端

上一章写了写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");
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值