Unity局域⽹传输图⽚等⽂件使⽤Unity实现局域⽹下传输各种⽂件,这⾥我传输图⽚为例,放上关键代码:
客户端代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using UnityEngine;
using System.IO;
using UnityEngine.SocialPlatforms;
//using LitJson;
namespace SocketServer
{
class Client
{
private const int BufferSize =1024;
private static byte[] result =new byte[1024];
static IPAddress ip = IPAddress.Parse("192.168.1.10");//192.168.1.10
static Socket clientSocket =null;
static IPEndPoint endPoint =new IPEndPoint(ip,8885);
public static void StartSendFile(string path)
{
Thread myThread =new Thread(new ParameterizedThreadStart(SendFile));
myThread.Start(path);
}
static void SendFile(object absPath)
{
string path =(string)absPath;
if(clientSocket ==null||!clientSocket.Connected)
{
getsavefilename
clientSocket =new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(endPoint);//配置服务器IP与端⼝
ClientManager.Instance.AddMessage("连接服务器成功");
Debug.Log("连接服务器成功");
}
catch
{
ClientManager.Instance.AddMessage("连接服务器失败");
Debug.Log("连接服务器失败");
return;
}
}
try
{
FileStream reader =new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None);
long send =0L, length = reader.Length;
string fileName = Path.GetFileName(path);
string sendStr ="Sending File,"+ fileName +","+ length.ToString();
Debug.Log(sendStr);
//ClientManager.Instance.AddMessage(sendStr);
clientSocket.Send(EncoderToByte(sendStr));
int BufferSize =1024;
int BufferSize =1024;
byte[] buffer =new byte[1024];
clientSocket.Receive(buffer);
string message =DecoderToString(buffer);
if(message.Contains("Ready for sending"))
{
Debug.Log("Sending File:"+ fileName +".");
ClientManager.Instance.AddMessage("Sending File:"+ fileName +".");
byte[] fileBuffer =new byte[BufferSize];
int read, sent;
while((read = reader.Read(fileBuffer,0, BufferSize))!=0)
{
sent =0;
while((sent += clientSocket.Send(fileBuffer, sent, read, SocketFlags.None))< read)
{
send +=(long)sent;
}
}
Debug.Log(fileName +" Send Finish");
ClientManager.Instance.AddMessage(fileName +" Send Finish");
}
else
{
Debug.Log(message);
}
reader.Flush();
reader.Close();
}
catch(Exception ex)
{
Debug.Log(ex.Message);
}
return;
}
public static List<ClientManager.FileInfomation>GetFileList()
{
if(clientSocket ==null||!clientSocket.Connected)
{
clientSocket =new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(endPoint);//配置服务器IP与端⼝
ClientManager.Instance.AddMessage("连接服务器成功");
Debug.Log("连接服务器成功");
}
catch
{
ClientManager.Instance.AddMessage("连接服务器失败");
Debug.Log("连接服务器失败");
return null;
}
}
clientSocket.Send(EncoderToByte("GetFileList"));
Debug.Log("Send Get List Request");
ClientManager.Instance.AddMessage("Send Get List Request");
byte[] buffer =new byte[1024];
clientSocket.Receive(buffer);
string message1 =DecoderToString(buffer);
Debug.Log(message1);
if(message1.Contains("FileListNull"))
if(message1.Contains("FileListNull"))
{
Debug.Log("FileListNull");
ClientManager.Instance.AddMessage("File list is null");
return null;
}
else if(message1.Contains("Sending List"))
{
byte[] buffer2 =new byte[1024];
clientSocket.Receive(buffer2);
string message2 =DecoderToString(buffer2);
Debug.Log(message2);
//Debug.Log(message);
return StringToList(message2);
}
else
{
return null;
}
}
public static void StartReceiveFile(ThreadHelper helper)
{
Thread myThread =new Thread(new ParameterizedThreadStart(ReceiveFile));
myThread.Start(helper);
}
static void ReceiveFile(object helper)
{
ThreadHelper myHelper =(ThreadHelper)helper;
string savePath = myHelper.savePath;
string requestName = questName;
if(File.Exists(Path.Combine(savePath, requestName)))
{
Debug.Log("There already has a same file");
ClientManager.Instance.AddMessage("There already has a same file");
return;
}
if(clientSocket ==null||!clientSocket.Connected)
{
clientSocket =new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(endPoint);//配置服务器IP与端⼝
Debug.Log("连接服务器成功");
ClientManager.Instance.AddMessage("连接服务器成功");
}
catch
{
Debug.Log("连接服务器失败");
ClientManager.Instance.AddMessage("连接服务器失败");
}
}
string request ="Download File"+","+ requestName +","+ requestName.Length;
Debug.Log(request);
clientSocket.Send(EncoderToByte(request));
byte[] buffer =new byte[1024];
clientSocket.Receive(buffer);
string message =DecoderToString(buffer);
string[] command = message.Split(',');
string[] command = message.Split(',');
string fileName = command[1];
long length;
fileName = command[1];
length = Convert.ToInt64(command[2]);
clientSocket.Send(EncoderToByte("Ready for sending"));
long receive =0L;
Debug.Log("Receiveing file:"+ fileName +".");
ClientManager.Instance.AddMessage("Receiveing file:"+ fileName +".");
FileStream writer =new FileStream(Path.Combine(savePath, fileName), FileMode.Create, FileAccess.Write, FileShare.None);
int received;
while(receive < length)
{
received = clientSocket.Receive(result);
writer.Write(result,0, received);
writer.Flush();
receive +=(long)received;
}
writer.Flush();
writer.Close();
ClientManager.Instance.AddMessage(fileName +" Receive Finish");
Debug.Log(fileName +" Receive Finish");
}
static void CloseSocket(Socket socket)
{
socket.Disconnect(true);
//socket.Shutdown(SocketShutdown.Both);
//socket.Close();
Debug.Log("Close Socket "+ socket.RemoteEndPoint.ToString());
}
static string DecoderToString(byte[] bytes)
{
char[] chs =new char[1024];
Decoder decoder = Encoding.UTF8.GetDecoder();
decoder.GetChars(bytes,0, bytes.Length, chs,0);
return new string(chs);
}
static byte[]EncoderToByte(string sendStr)
{
Encoder encoder = Encoding.UTF8.GetEncoder();
char[] sendChar = sendStr.ToCharArray();
byte[] bytes =new byte[encoder.GetByteCount(sendChar,0, sendChar.Length,true)];
encoder.GetBytes(sendChar,0, sendChar.Length, bytes,0,true);
return bytes;
}
static List<ClientManager.FileInfomation>StringToList(string str)
{
string[] keys = str.Split(',');
List<ClientManager.FileInfomation> list =new List<ClientManager.FileInfomation>();
int i =0;
while(i < keys.Length -1)
{
list.Add(new ClientManager.FileInfomation(keys[i], keys[i +1]));
i +=2;
}
return list;
}
}
public struct ThreadHelper
public struct ThreadHelper
{
public string savePath;
public string requestName;
public ThreadHelper(string path,string name)
{
savePath = path;
requestName = name;
}
}
}
服务端代码:
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using UnityEngine;
using System.IO;
//using LitJson;
using UnityEngine.UI;
namespace SocketServer
{
class Server
{
private static byte[] result =new byte[1024];
private static int myProt =8885;//端⼝
static Socket serverSocket;
private const int BufferSize =1024;
//public const string savePath = @"C:\Users\Administrator\Desktop\学习\⾯向对象\Socket\Save";
public static Thread StartServer()
{
//服务器IP地址
IPAddress ip = IPAddress.Parse("192.168.1.10");//192.168.1.10
serverSocket =new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            serverSocket.Bind(new IPEndPoint(ip, myProt));//绑定IP地址:端⼝
serverSocket.Listen(10);//设定最多10个排队连接请求
Debug.Log("启动监听成功"+ serverSocket.LocalEndPoint.ToString());
ServerManager.Instance.AddMessage("启动监听成功"+ serverSocket.LocalEndPoint.ToString());
//通过Clientsoket发送数据
Thread myThread =new Thread(ListenClientConnect);
myThread.Start();
return myThread;
}
/// <summary>
/// 监听客户端连接
/// </summary>
private static void ListenClientConnect()
{
//Socket clientSocket = serverSocket.Accept();
//ReceiveMessage(clientSocket);
while(true)
{
Socket clientSocket = serverSocket.Accept();
if(clientSocket.Connected)
{
Thread receiveThread =new Thread(ReceiveMessage);

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。