Scoket 服务器监听多个客户端发来的图片
这是服务器 直接上代码 都有详细注释 注意线程需要自己手动关闭 不然程序会卡死
/* #########
############
#############
## ###########
### ###### #####
### ####### ####
### ########## ####
#### ########### ####
#### ########### #####
##### ### ######## #####
##### ### ######## ######
###### ### ########### ######
###### #### ############## ######
####### ##################### ######
####### ###################### ######
####### ###### ################# ######
####### ###### ###### ######### ######
####### ## ###### ###### ######
####### ###### ##### #####
###### ##### ##### ####
##### #### ##### ###
##### ### ### #
### ### ###
## ### ###
__________#_______####_______####______________
身是菩提树,心如明镜台,时时勤拂拭,勿使惹尘埃。
我们的未来没有BUG
* ==============================================================================
* Filename: SocketServers
* Created: $time$
* Author: WYC
* Purpose: scoket服务器监听端口脚本
* ==============================================================================
*/
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using UnityEngine;
public class SocketServers : MonoBehaviour
{
//图片保存的地址与名字
private string IpStr = "192.168.2.224";
private Socket serverSocket;
private Thread thread;
void Start () {
//desPathName.Replace("/","\\");
//Debug.Log(desPathName);
IPAddress ip = IPAddress.Parse(IpStr);
IPEndPoint ip_end_point = new IPEndPoint(ip, 8080);
//创建服务器Socket对象,并设置相关属性
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//绑定ip和端口
serverSocket.Bind(ip_end_point);
//设置最长的连接请求队列长度
serverSocket.Listen(10);
Debug.Log("启动监听" + serverSocket.LocalEndPoint.ToString() + "成功");
//在新线程中监听客户端的连接
Thread thread = new Thread(ClientConnectListen);
thread.Start();
}
/// <summary>
/// 客户端连接请求监听
/// </summary>
private void ClientConnectListen()
{
while (true)
{
//为新的客户端连接创建一个Socket对象
Socket clientSocket = serverSocket.Accept();
clientSocket.ReceiveBufferSize = 1024 * 1024 ;
Debug.Log("客户端" + clientSocket.RemoteEndPoint.ToString() + "成功连接");
//每个客户端连接创建一个线程来接受该客户端发送的消息
thread = new Thread(RecieveMessage);
thread.Start(clientSocket);
}
}
private static byte[] bttess1;
private static byte[] bttess2;
private static byte[] bttess3;
/// <summary>
/// 接收指定客户端Socket的消息
/// </summary>
/// <param name="clientSocket"></param>
private static void RecieveMessage(object clientSocket)
{
Socket mClientSocket = (Socket)clientSocket;
while (true)
{
try
{
byte[] bytes = new byte[1536 * 2048];
int receiveNumber = mClientSocket.Receive(bytes);
Debug.Log("接收客户端" + mClientSocket.RemoteEndPoint.ToString().Substring(0, 11));
MemoryStream fs = new MemoryStream();
fs.Write(bytes, 0, receiveNumber);
if (mClientSocket.RemoteEndPoint.ToString().Substring(0, 12) == "192.168.2.41")
{
bttess1 = fs.ToArray();
dinosaur = Dinosaur.One;
}
if (mClientSocket.RemoteEndPoint.ToString().Substring(0, 13) == "192.168.2.224")
{
bttess2 = fs.ToArray();
dinosaur = Dinosaur.Two;
}
if (mClientSocket.RemoteEndPoint.ToString().Substring(0, 12) == "192.168.2.46")
{
bttess3 = fs.ToArray();
dinosaur = Dinosaur.Thress;
}
//Debug.Log("fs");
//从内存中再次将数据读出来并保存为jpg图片
//注意 这里 无法保存在C盘
//System.Drawing.Image Img = System.Drawing.Image.FromStream(fs);
//image = System.Drawing.Image.FromStream(fs);
//Img.Save(desPathName, ImageFormat.Jpeg);
Debug.Log("保存完毕!!!");
fs.Close();
}
catch (Exception ex)
{
Debug.Log(ex.Message + "有一个退出了:这是一个异常");
dinosaur = Dinosaur.None;
mClientSocket.Shutdown(SocketShutdown.Both);
mClientSocket.Close();
break;
}
//这里开辟了1M的字节空间 也就是一次图片的传输最大是1M大小
}
}
public GameObject[] perfab;
private static Dinosaur dinosaur = Dinosaur.None;
private void Update()
{
switch (dinosaur)
{
case Dinosaur.None:
break;
case Dinosaur.One:
Debug.Log("1");
GameObject obj = Instantiate(perfab[0],new Vector3(0,0,0),Quaternion.identity);
Texture2D texture = new Texture2D(1536, 2048);
texture.LoadImage(bttess1);
obj.transform.GetComponent<MerteiShader>().generateTexture(texture);
dinosaur = Dinosaur.None;
break;
case Dinosaur.Two:
Debug.Log("2");
GameObject obj1 = Instantiate(perfab[1],new Vector3(0, 10, 0), Quaternion.identity);
Texture2D texture2 = new Texture2D(1536, 2048);
texture2.LoadImage(bttess2);
obj1.transform.GetComponent<MerteiShader>().generateTexture(texture2);
dinosaur = Dinosaur.None;
break;
case Dinosaur.Thress:
Debug.Log("3");
GameObject obj2 = Instantiate(perfab[2],new Vector3(0, 20, 0), Quaternion.identity);
Texture2D texture3 = new Texture2D(1536, 2048);
texture3.LoadImage(bttess3);
obj2.transform.GetComponent<MerteiShader>().generateTexture(texture3);
dinosaur = Dinosaur.None;
break;
default:
break;
}
}
public void setAbort()
{
if (thread != null)
{
thread.Abort();
}
}
void OnDestroy()
{
Debug.Log(" 脚本以关闭");
setAbort();
}
}
enum Dinosaur
{
None=0,
One=1,
Two=2,
Thress=3
}
客户端处理是摄像机拍照转成byte[]字节流发送
/* #########
############
#############
## ###########
### ###### #####
### ####### ####
### ########## ####
#### ########### ####
#### ########### #####
##### ### ######## #####
##### ### ######## ######
###### ### ########### ######
###### #### ############## ######
####### ##################### ######
####### ###################### ######
####### ###### ################# ######
####### ###### ###### ######### ######
####### ## ###### ###### ######
####### ###### ##### #####
###### ##### ##### ####
##### #### ##### ###
##### ### ### #
### ### ###
## ### ###
__________#_______####_______####______________
身是菩提树,心如明镜台,时时勤拂拭,勿使惹尘埃。
我们的未来没有BUG
* ==============================================================================
* Filename: CameraManger
* Created: $time$
* Author: WYC
* Purpose:
* ==============================================================================
*/
using System.IO;
using System.Net;
using System.Net.Sockets;
using UnityEngine;
using UnityEngine.UI;
public class CameraManger : MonoBehaviour
{
private string IpStr = "192.168.2.224";
public Camera camera1;
public Rect rect;
private TcpClient client;
private byte [] _byte;
private bool bIsInCD = false;
public float TimeSpeed = 3;
public Image _Sprite;
public Text Lable;
public RawImage Phonte;
public GameObject[] GameObj;
public Text BaocaoLable;
//关闭待机画面
public void CloseStandby() {
GameObj[0].SetActive(false);
// OpenCamera.instance.cameraSwitch();
}
//重拍
public void Rephotograph() {
GameObj[1].SetActive(false);
GameObj[2].SetActive(true);
GameObj[3].SetActive(true);
//OpenCamera.instance.Play();
}
//上传服务器
public void SendStreamToServer()
{
Rephotograph();
//try
//{
// NetworkStream streamToServer = client.GetStream();//获得客户端的流
// streamToServer.Write(_byte, 0, _byte.Length);//将转换好的二进制数据写入流中并发送
// Debug.Log("发出图片");
// BaocaoLable.text = "发出图片成功";
//}
//catch (Exception ex)
//{
// Debug.Log("服务端产生异常:" + ex.Message);
// BaocaoLable.text = "服务端产生异常:" + ex.Message;
//}
try
{
//发送数据
clientMsg.Send(_byte);
BaocaoLable.text = "发出图片成功";
}
catch (SocketException e)
{
BaocaoLable.text = e.Data.ToString();
clientMsg.Shutdown(System.Net.Sockets.SocketShutdown.Send);
clientMsg.Close();
clientMsg = null;
}
}
//拍照
public void GetPhonte()
{
bIsInCD = true;
_Sprite.fillAmount = 1;
}
//倒计时开始拍照
private void StartCD()
{
if (bIsInCD)
{
_Sprite.fillAmount -= (1f / TimeSpeed) * Time.deltaTime;//对图片按照时间进行360度的旋转剪切
Lable.text = (TimeSpeed * _Sprite.fillAmount).ToString("F0");//改变冷却时间
if (_Sprite.fillAmount <= 0.05f)
{
bIsInCD = false;
_Sprite.fillAmount = 0;
Lable.text = "";
TakePhotos();
}
}
}
//拍照获取获取照片
private void TakePhotos()
{
GameObj[2].SetActive(false);
GameObj[3].SetActive(false);
// 创建一个RenderTexture对象
RenderTexture rt = new RenderTexture((int)rect.width, (int)rect.height, 0);
// 临时设置相关相机的targetTexture为rt, 并手动渲染相关相机
camera1.targetTexture = rt;
camera1.Render();
// 激活这个rt, 并从中中读取像素。
RenderTexture.active = rt;
Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
screenShot.ReadPixels(rect, 0, 0);// 注:这个时候,它是从RenderTexture.active中读取像素
screenShot.Apply();
// 重置相关参数,以使用camera继续在屏幕上显示
camera1.targetTexture = null;
RenderTexture.active = null; // JC: added to avoid errors
GameObject.Destroy(rt);
_byte = screenShot.EncodeToPNG();
Phonte.texture = screenShot;
GameObj[1].SetActive(true);
//OpenCamera.instance.Stop();
}
private Socket clientMsg;
void Start()
{
IPEndPoint ipendpiont = new IPEndPoint(IPAddress.Parse(IpStr), 8080);
clientMsg = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientMsg.Connect(ipendpiont);
//client = new TcpClient();
//try
//{
// client.Connect(IPAddress.Parse("192.168.2.224"), 8080);//同步方法,连接成功、抛出异常、服务器不存在等之前程序会被阻塞
//}
//catch (Exception ex)
//{
// Debug.Log("客户端连接异常:" + ex.Message);
// BaocaoLable.text = "客户端连接异常:" + ex.Message;
//}
//Debug.Log("LocalEndPoint = " + client.Client.LocalEndPoint + ". RemoteEndPoint = " + client.Client.RemoteEndPoint);
//BaocaoLable.text = "LocalEndPoint = " + client.Client.LocalEndPoint + ". RemoteEndPoint = " + client.Client.RemoteEndPoint;
}
void Update()
{
StartCD();
}
}
当时俩者之间传输 问题不断 我这个只能算是参考 谢谢指教