不熟悉TCP/UDP协议的同学可以参考这篇文章:http://blog.csdn.net/li_ning_/article/details/52117463
话不多少说,服务器端代码如下:
using UnityEngine;
using System.Collections;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System;
public class TCPServer : MonoBehaviour {
private TcpListener tcpListener = null;
private TcpClient tcpClient = null;
private Thread thread_tcpRecv = null;
private bool isRunningThread = false;
private Queue<string> queue_tcpMessages;
// Use this for initialization
void Start () {
queue_tcpMessages = new Queue<string>();
CreateTcpListen();
}
// Update is called once per frame
void Update () {
if (queue_tcpMessages.Count > 0)
{
string cmd = queue_tcpMessages.Dequeue();
print(cmd);
DoByCommand(cmd);
}
}
void DoByCommand(string cmd)
{
switch (cmd)
{
case "TransPortPhoto": ReceivePhoto(); break; //图片数据流的接收并显示
}
}
void ReceivePhoto()
{
Debug.Log("DisPlay Photo");
}
void ReciveMessages()
{
while(isRunningThread)
{
try
{
tcpClient = tcpListener.AcceptTcpClient();
byte[] buffer = new Byte[tcpClient.ReceiveBufferSize];
NetworkStream dataStream = tcpClient.GetStream();
dataStream.Read(buffer, 0, buffer.Length);
queue_tcpMessages.Enqueue(System.Text.Encoding.Default.GetString(buffer).Trim('\0'));
dataStream.Close();
tcpClient.Close();
}
catch(System.Exception ex)
{
print(ex.Message);
break;
}
}
}
void CreateTcpListen()
{
isRunningThread = true;
tcpListener = new TcpListener(IPAddress.Parse(ConfiInfo.serverIP), ConfiInfo.TcpPort);
tcpListener.Start();
thread_tcpRecv = new Thread(ReciveMessages);
thread_tcpRecv.Start();
}
void OnDisable()
{
isRunningThread = false;
tcpListener.Stop();
}
}
客户端代码如下:
using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
public class TCPClient : MonoBehaviour {
private TcpClient tcpClient = null;
// Use this for initialization
void Start () {
CreateTcpClient();
}
// Update is called once per frame
void Update () {
}
public void SendTcpMessages()
{
SendTcpStringMessage("TransPortPhoto");
}
void SendTcpStringMessage(string meg) //发送字符串信息
{
byte[] sendData = System.Text.Encoding.Default.GetBytes(meg);
tcpClient = new TcpClient();
try
{
tcpClient.Connect(IPAddress.Parse(ConfiInfo.serverIP), ConfiInfo.TcpPort);
}
catch (System.Exception ex)
{
print(ex);
//break;
}
NetworkStream dataStream = tcpClient.GetStream();
dataStream.Write(sendData, 0, sendData.Length);
dataStream.Close();
tcpClient.Close();
}
void CreateTcpClient()
{
}
void OnDestory()
{
}
}