Unity&Socket使用TCP通信学记一

//服务端代码
using UnityEngine;
using System;
using System.Net;  
using System.Net.Sockets;  
using System.Text;  
using System.Threading;
using ProtoBuf; 
using System.Collections.Generic;

public class TCPServerTest : MonoBehaviour {
	Socket serverSocket;
	Socket clientSocket;
	Thread clientThread;
	Thread t;
	// Use this for initialization
	void Start () {
		t = new Thread(new ThreadStart(OpenServer));
		t.Start();
	}
	
	// Update is called once per frame
	void Update () {
	
	}
	void OnDestroy(){
		t.Abort();
<span style="white-space:pre">		</span>serverSocket.Close();
	}

	void OpenServer(){
		IPAddress ipAdr = IPAddress.Parse("127.0.0.1");  
		IPEndPoint ipEp = new IPEndPoint(ipAdr , 2234);
		serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
		serverSocket.Bind(ipEp);
		serverSocket.Listen(10);

		while(true){
			try {
				clientSocket = serverSocket.Accept();
				Debug.Log("Accept");
				clientThread = new Thread(new ThreadStart(ReceiveData));
				clientThread.Start ();

			} catch (System.Exception ex) {
				print(ex);
			}
		}
	}

	void ReceiveData(){
		bool keepalive = true;
		Socket s = clientSocket;
		byte[] buffer = new byte[1024];

		//根据收听到的客户端套接字向客户端发送信息
		IPEndPoint clientep = (IPEndPoint)s.RemoteEndPoint;
		//lstServer.Items.Add("Client:" + clientep.Address + "("+clientep.Port+")");
		string welcome = "IP为"+clientep.Address +"的客户端连接成功";
		byte[] data = new byte[1024];
		data = Encoding.UTF8.GetBytes(welcome);
		s.Send(data, data.Length, SocketFlags.None);

		while (keepalive)
		{
			//在套接字上接收客户端发送的信息
			int bufLen = 0;
			try
			{
				bufLen = s.Available;

				s.Receive(buffer, 0, bufLen, SocketFlags.None);
				if (bufLen == 0)
					continue;
			}
			catch (Exception ex)
			{
				Debug.Log("Receive Error:" + ex.Message);
				return;
			}
			clientep = (IPEndPoint)s.RemoteEndPoint;
			string clientcommand = System.Text.Encoding.UTF8.GetString(buffer).Substring(0, bufLen);
			Debug.Log("服务端收到:" +clientcommand);
			//lstServer.Items.Add(clientcommand + "("+clientep.Address + ":"+clientep.Port+")");

		}
	}
}


//客户端代码
using UnityEngine;
using System;
using System.Net;  
using System.Net.Sockets;  
using System.Text;  
using System.Threading;
using ProtoBuf; 
using System.Collections.Generic;

public class TCPClientTest : MonoBehaviour {
	Socket clientSocket;
	byte[] sdata = new byte[1024];
	Thread t;
	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {
	
	}

	void ConnectServer(){
		IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2234);
		clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		try
		{
			clientSocket.Connect(ipep);
		}
		catch (SocketException ex)
		{
			Debug.Log("connect error: " + ex.Message);
			return;
		}

		while (true)
		{
			//接收服务器信息
			int bufLen = 0;
			try
			{
				bufLen = clientSocket.Available;
				clientSocket.Receive(sdata, 0, bufLen, SocketFlags.None);
				if (bufLen == 0)
				{
					continue;
				}
			}
			catch (Exception ex)
			{
				Debug.Log("Receive Error:" + ex.Message);
				return;
			}
			string clientcommand = System.Text.Encoding.UTF8.GetString(sdata).Substring(0, bufLen);
			Debug.Log("客户端收到:" + clientcommand);
			//lstClient.Items.Add(clientcommand);
		}
	}

	void sendMsg(){
		byte[] data = new byte[1024];
		data = Encoding.UTF8.GetBytes(sendStr);
		clientSocket.Send(data, data.Length, SocketFlags.None);
	}

	string sendStr = "Send SomeThing";
	void OnGUI(){
		if(GUILayout.Button("Connect"))
		{
			t = new Thread(new ThreadStart(ConnectServer));
			t.Start();
		}
		sendStr = GUILayout.TextArea(sendStr);
		if(GUILayout.Button("send"))
		{
			sendMsg();
		}
	}

	void OnDestroy(){
		t.Abort();
<span style="white-space:pre">		</span>if(clientSocket!=null){
<span style="white-space:pre">			</span>clientSocket.Close();
<span style="white-space:pre">		</span>}
	}
}


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值