【游戏技术群】959392658  【游戏出海群】12067810
游戏蛮牛 手机端
开启辅助访问
 找回密码
 注册帐号

扫一扫,访问微社区

首页   >   博客   >   18803836360

udp 传输数据 net +修改

个人分类: 网络 | 2018-12-20 21:15

客户端代码

[code]csharpcode:

using UnityEngine; 
using System.Collections; 
//引入库 
using System.Net; 
using System.Net.Sockets; 
using System.Text; 
using System.Threading;
using System.Collections.Generic;
using UnityEngine.UI;
public class UdpClient : MonoBehaviour {

	string editString = "hello wolrd"; //编辑框文字

	public Text testText;
	//以下默认都是私有的成员
	private	Socket socket; //目标socket

	#region 服务端
	//EndPoint serverEnd; 
	#endregion

	#region 服务端端口

	#endregion 
	string recvStr; //接收的字符串
	string sendStr; //发送的字符串
	byte[] recvData = new byte[1024]; //接收的数据,必须为字节
	byte[] sendData = new byte[1024]; //发送的数据,必须为字节
	int recvLen; //接收的数据长度
	Thread connectThread; //连接线程
	string localIP="";
	void Awake()
	{
		localIP = Network.player.ipAddress.ToString ();
		Debug.Log (localIP);
	}

	/// <summary>
	/// 使用一个socket,利用不用的endpoint  在发送数据时将本机作为客户端,在接收数据时将本机作为客户端
	/// </summary>
	void InitSocket()
	{
		#region定义连接的服务器ip和端口,可以是本机ip,局域网,互联网
		//Debug.Log ("接受数据时使用监听全部");
		IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any,8001);
		#endregion

		#region 定义套接字类型,在主线程中定义
		socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
		#endregion
        socket.Bind(ipEnd);
		Debug.Log("waiting for sending UDP dgram");

		#region建立初始连接,这句非常重要,第一次连接初始化了serverEnd后面才能收到消息
		SocketSend("hello");
		#endregion

		#region开启一个线程连接,必须的,否则主线程卡死
		connectThread = new Thread(new ThreadStart(SocketReceive));
		connectThread.Start();
		#endregion
	}
	private Socket serverSocket = new Socket (AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp); 



	void SocketSend(string sendStr)
	{
		//Debug.Log ("发送时监听使用广播");
		#region    接受数据时将本机定义服务端        侦听的端口
		IPEndPoint sender = new IPEndPoint(IPAddress.Broadcast,1234);
		#endregion

		//清空发送缓存
		sendData = new byte[1024];
		//数据类型转换
		sendData = Encoding.ASCII.GetBytes(sendStr);
		//发送给指定服务端
		serverSocket.SetSocketOption (SocketOptionLevel.Socket,SocketOptionName.Broadcast,1);
		serverSocket.SendTo (sendData, sender);
		//serverSocket.SendTo(sendData, sendData.Length, SocketFlags.None,ipEnd);
	}

	#region  字符串包装为指定格式
	private void StringToByte(string _str,string _format)
	{
		switch (_format) 
		{
		case "SCORE":
			PackageStringOne (_str);
			break;
		case "LEAVE":
			PackageStringTwo (_str);
			break;
		case "2":
			PackageStringThree (_str);
			break;
		case "3":
			PackageStringFour (_str);
			break;
		case "4":
			PackageStringFive (_str);
			break;
		case "5":
			PackageStringSix (_str);
			break;

		}

	}

	#region 六种包装数据的方式
	private void PackageStringOne(string _strs)
	{
		string str = "SCORE ";
		str += _strs+" ";
		byte[] needSendByte=System.Text.Encoding.UTF8.GetBytes (str);
		//socket.SendTo(needSendByte, needSendByte.Length, SocketFlags.None, ipEnd);

	}
	private void PackageStringTwo(string _strs)
	{
		string str = "LEAVE ";
		str += _strs+" ";
		byte[] needSendByte=System.Text.Encoding.UTF8.GetBytes (str);
		//socket.SendTo(needSendByte, needSendByte.Length, SocketFlags.None, ipEnd);

	}
	private void PackageStringThree(string _strs)
	{
		string str = "SCORE ";
		str += _strs+" ";
		byte[] needSendByte=System.Text.Encoding.UTF8.GetBytes (str);
		//socket.SendTo(needSendByte, needSendByte.Length, SocketFlags.None, ipEnd);

	}
	private void PackageStringFour(string _strs)
	{
		string str = "SCORE ";
		str += _strs+" ";
		byte[] needSendByte=System.Text.Encoding.UTF8.GetBytes (str);
		//socket.SendTo(needSendByte, needSendByte.Length, SocketFlags.None, ipEnd);
	}
	private void PackageStringFive(string _strs)
	{
		string str = "SCORE ";
		str += _strs+" ";
		byte[] needSendByte=System.Text.Encoding.UTF8.GetBytes (str);
		//socket.SendTo(needSendByte, needSendByte.Length, SocketFlags.None, ipEnd);
	}
	private void PackageStringSix(string _strs)
	{
		string str = "SCORE ";
		str += _strs+" ";
		byte[] needSendByte=System.Text.Encoding.UTF8.GetBytes (str);
		//socket.SendTo(needSendByte, needSendByte.Length, SocketFlags.None, ipEnd);
	}
	#endregion

	#endregion



	#region    服务器接收     处理存储到列表的消息

	public List<string> llReceive = new List<string> ();
	void SocketReceive()
	{
		//进入接收循环
		while (true)
		{
			EndPoint serverEnd = new IPEndPoint (IPAddress.Any,8001);
			//对data清零
			recvData = new byte[1024];
			//获取客户端,获取服务端端数据,用引用给服务端赋值,实际上服务端已经定义好并不需要赋值
			recvLen = socket.ReceiveFrom(recvData, ref serverEnd);
			Debug.Log("message from: " + serverEnd.ToString()); //打印服务端信息 
			//输出接收到的数据
			recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen);

			llReceive.Add (recvStr);

			Debug.Log("我是客户端,接收到服务器的数据"+recvStr);
		}
	}
	private void HandleList()
	{
		if (llReceive.Count <= 0) 
		{
			return;
		}
		string strFirst = llReceive [0];
		llReceive.RemoveAt (0);


		string [] strArray=strFirst.Split (' ');
		handByFormat (strArray,strArray[0]);

	}

	public void handByFormat(string [] _str,string _format)
	{
		switch(_format)
		{
		case "1":
			handleOne (_str);
			break;
		case "2":
			handleTwo (_str);
			break;
		case "3":
			handleThree (_str);
			break;
		case "4":
			handleFour (_str);
			break;
		case "5":
			handleFive (_str);
			break;
		case "6":
			handleSix (_str);
			break;
		default:
			break;
		}
	}
	private void handleOne(string[] _strt)
	{

	}

	private void handleTwo(string[] _strt)
	{

	}

	private void handleThree(string[] _strt)
	{

	}

	private void handleFour(string[] _strt)
	{

	}

	private void handleFive(string[] _strt)
	{

	}

	private void handleSix(string[] _strt)
	{

	}

	#endregion



	#region连接关闭
	void SocketQuit()
	{
		//关闭线程
		if (connectThread != null)
		{
			connectThread.Interrupt();
			connectThread.Abort();
		}
		//最后关闭socket
		if (socket != null)
			socket.Close();
		if (serverSocket != null)
			serverSocket.Close();
	}
	#endregion


	void Start()
	{
		InitSocket(); //在这里初始化
	}

	void OnGUI()
	{
		editString = GUI.TextField(new Rect(10, 10, 100, 20), editString);
		if (GUI.Button(new Rect(10, 30, 60, 20), "send"))
			SocketSend(editString);
	}
		
	void Update()
	{
		testText.text = recvStr;
	}

	void OnApplicationQuit()
	{
		SocketQuit();
	}

}
服务端代码

[code]csharpcode:

using System.Collections; 
//引入库 
using System.Net; 
using System.Net.Sockets; 
using System.Text; 
using System.Threading;
using UnityEngine;
using System.Collections.Generic;
public class UdpServer : MonoBehaviour {

	//以下默认都是私有的成员 
	Socket Receivesocket; //目标socket 


	string recvStr; //接收的字符串 
	string sendStr; //发送的字符串 
	byte[] recvData = new byte[1024]; //接收的数据,必须为字节 
	byte[] sendData = new byte[1024]; //发送的数据,必须为字节 
	int recvLen; //接收的数据长度 
	Thread connectThread; //连接线程
	//初始化

	string localIP;
	void Awake()
	{
		localIP = Network.player.ipAddress.ToString ();
	}

	void InitSocket()
	{
		#region定义侦听端口,侦听任何IP
//		Debug.Log ("接受数据的端口");
		IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 1234);
		#endregion

		#region定义套接字类型,在主线程中定义
		Receivesocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
		#endregion

		#region服务端需要绑定ip
		Receivesocket.Bind(ipEnd);
		#endregion

		#region定义客户端

		Debug.Log("waiting for UDP dgram");
		#region开启一个线程连接,必须的,否则主线程卡死
		connectThread = new Thread(new ThreadStart(SocketReceive));
		connectThread.Start();
		#endregion
	}

	private Socket SendSocket = new Socket (AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
	#region 发送消息时对消息进行包装
	void SocketSend(string sendStr)
	{
		//为客户端 申请的IP    用来接收消息
		EndPoint sender = new IPEndPoint(IPAddress.Broadcast,8001);
		#endregion
		//清空发送缓存
		sendData = new byte[1024];
		//数据类型转换
		sendData = Encoding.ASCII.GetBytes(sendStr);
		//发送给指定客户端
		SendSocket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.Broadcast, 1);

		SendSocket.SendTo (sendData,sender);
	}
	#region  字符串包装为指定格式
	private void StringToByte(string _str,string _format)
	{
		switch (_format) 
		{
		case "SCORE":
			PackageStringOne (_str);
			break;
		case "LEAVE":
			PackageStringTwo (_str);
			break;
		case "2":
			PackageStringThree (_str);
			break;
		case "3":
			PackageStringFour (_str);
			break;
		case "4":
			PackageStringFive (_str);
			break;
		case "5":
			PackageStringSix (_str);
			break;
		default:
			break;
		}

	}

	#region 六种包装数据的方式
	private void PackageStringOne(string _strs)
	{
		string str = "SCORE ";
		str += _strs+" ";
		byte[] needSendByte=System.Text.Encoding.ASCII.GetBytes (str);
		//socket.SendTo(needSendByte, needSendByte.Length, SocketFlags.None, clientEnd);

	}
	private void PackageStringTwo(string _strs)
	{
		string str = "LEAVE ";
		str += _strs+" ";
		byte[] needSendByte=System.Text.Encoding.ASCII.GetBytes (str);
		//socket.SendTo(needSendByte, needSendByte.Length, SocketFlags.None, clientEnd);

	}
	private void PackageStringThree(string _strs)
	{
		string str = "SCORE ";
		str += _strs+" ";
		byte[] needSendByte=System.Text.Encoding.ASCII.GetBytes (str);
		//socket.SendTo(needSendByte, needSendByte.Length, SocketFlags.None, clientEnd);

	}
	private void PackageStringFour(string _strs)
	{
		string str = "SCORE ";
		str += _strs+" ";
		byte[] needSendByte=System.Text.Encoding.ASCII.GetBytes (str);
		//socket.SendTo(needSendByte, needSendByte.Length, SocketFlags.None, clientEnd);
	}
	private void PackageStringFive(string _strs)
	{
		string str = "SCORE ";
		str += _strs+" ";
		byte[] needSendByte=System.Text.Encoding.ASCII.GetBytes (str);
		//socket.SendTo(needSendByte, needSendByte.Length, SocketFlags.None, clientEnd);
	}
	private void PackageStringSix(string _strs)
	{
		string str = "SCORE ";
		str += _strs+" ";
		byte[] needSendByte=System.Text.Encoding.ASCII.GetBytes (str);
		//socket.SendTo(needSendByte, needSendByte.Length, SocketFlags.None, clientEnd);

	}
	#endregion

	#endregion
	#endregion


	#region                  服务器接收  处理消息
	void SocketReceive()
	{
		//进入接收循环
		while (true)
		{
			EndPoint ipEnd = new IPEndPoint (IPAddress.Any,1234);
			//对data清零
			recvData = new byte[1024];
			//获取客户端,获取客户端数据,用引用给客户端赋值
			recvLen = Receivesocket.ReceiveFrom(recvData, ref ipEnd);
			Debug.Log("message from: " + ipEnd.ToString()); //打印客户端信息

			//输出接收到的数据
			recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen);

			llReceive.Add (recvStr);

			Debug.Log("我是服务器,接收到客户端的数据"+recvStr);
			//将接收到的数据经过处理再发送出去
			sendStr = "From Server: " + recvStr;
			SocketSend(sendStr);
		}
	}

	public List<string> llReceive = new List<string> ();
	private void HandleList()
	{
		if (llReceive.Count <= 0) 
		{
			return;
		}
		string strFirst = llReceive [0];
		llReceive.RemoveAt (0);


		string [] strArray=strFirst.Split (' ');
		handByFormat (strArray,strArray[0]);

	}

	public void handByFormat(string [] _str,string _format)
	{
		switch(_format)
		{
		case "1":
			handleOne (_str);
			break;
		case "2":
			handleTwo (_str);
			break;
		case "3":
			handleThree (_str);
			break;
		case "4":
			handleFour (_str);
			break;
		case "5":
			handleFive (_str);
			break;
		case "6":
			handleSix (_str);
			break;
		default:
			break;
		}
	}
	private void handleOne(string[] _strt)
	{

	}

	private void handleTwo(string[] _strt)
	{

	}

	private void handleThree(string[] _strt)
	{

	}

	private void handleFour(string[] _strt)
	{

	}

	private void handleFive(string[] _strt)
	{

	}

	private void handleSix(string[] _strt)
	{

	}


	#endregion
	//连接关闭
	void SocketQuit()
	{
		//关闭线程
		if (connectThread != null)
		{
			connectThread.Interrupt();
			connectThread.Abort();
		}
		//最后关闭socket
		if (Receivesocket != null)
			Receivesocket.Close();
		if (SendSocket != null)
			SendSocket.Close ();
		print("disconnect");
	}


	void Start()
	{
		InitSocket(); 

		SocketSend ("无武器");
	}
	void OnApplicationQuit()
	{
		SocketQuit();
	}
	void OnDestroy()
	{
		
	}
}

0 0

作者的其他最新博客

评论 (0 个评论)

facelist doodle 涂鸦板

您需要登录后才可以评论 登录 | 注册帐号

个人分类

标签

阅读排行

评论排行

推荐博客

最新博客

返回顶部