使用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)
{
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;
byte[] buffer = new byte[1024];
clientSocket.Receive(buffer);
string message = DecoderToString(buffer);
if (message.Contains("Ready for sending"))
{
Debug.Log("Sending File:" + fileName + ".Plz wait...");
ClientManager.Instance.AddMessage("Sending File:" + fileName + ".Plz wait...");
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"))
{
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 = myHelper.requestName;
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 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 + ".Plz wait...");
ClientManager.Instance.AddMessage("Receiveing file:" + fileName + ".Plz wait...");
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 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);
receiveThread.Start(clientSocket);
}
}
}
/// <summary>
/// 接收消息
/// </summary>
/// <param name="clientSocket"></param>
static void ReceiveMessage(object clientSocket)
{
Socket myClientSocket = (Socket)clientSocket;
string clientName = myClientSocket.RemoteEndPoint.ToString();
while (true)
{
try
{
//通过clientSocket接收数据
byte[] buffer = new byte[1024];
myClientSocket.Receive(buffer);
string message = DecoderToString(buffer);
Debug.Log("接收消息:" + message);
if (message.Contains("Sending File"))
{
ReceiveFile(message, myClientSocket);
}
else if(message.Contains("GetFileList"))
{
SendFileList(myClientSocket);
}
else if(message.Contains("Download File"))
{
SendFile(message, myClientSocket);
}
//else
//{
// Debug.Log("接收客户端消息" + myClientSocket.RemoteEndPoint.ToString() + message);
//}
}
catch (Exception ex)
{
Debug.Log(clientName + "disconnect (" + ex.Message + ")");
//if(myClientSocket.Connected)
//{
// myClientSocket.Shutdown(SocketShutdown.Both);
// myClientSocket.Close();
//}
return;
}
}
}
static void SendFileList(Socket myClientSocket)
{
if(ServerManager.Instance.FileList.Count == 0)
{
myClientSocket.Send(EncoderToByte("FileListNull"));
}
else
{
myClientSocket.Send(EncoderToByte("Sending List"));
}
string fileListStr = ListToString(ServerManager.Instance.FileList);
Debug.Log(fileListStr);
myClientSocket.Send(EncoderToByte(fileListStr));
ServerManager.Instance.AddMessage("Send File List Finish");
Debug.Log("Send File List Finish");
}
static void ReceiveFile(string message, Socket myClientSocket)
{
Debug.Log("接收文件");
string[] command = message.Split(',');
string fileName = command[1];
long length;
fileName = command[1];
length = Convert.ToInt64(command[2]);
//if (File.Exists(Path.Combine(ServerManager.Instance.savePath, fileName)))
//{
// myClientSocket.Send(EncoderToByte("There has already a file named " + fileName));
// Debug.Log("There has already a file named " + fileName + ", stop receiving");
// ServerManager.Instance.AddMessage("There has already a file named " + fileName + ", stop receiving");
// //CloseSocket(myClientSocket);
// return;
//}
myClientSocket.Send(EncoderToByte("Ready for sending"));
long receive = 0L;
Debug.Log("Receiveing file:" + fileName + ".Plz wait...");
ServerManager.Instance.AddMessage("Receiveing file:" + fileName + ".Plz wait...");
FileStream writer = new FileStream(Path.Combine(ServerManager.Instance.savePath, fileName), FileMode.Create, FileAccess.Write, FileShare.None);
int received;
while (receive < length)
{
received = myClientSocket.Receive(result);
writer.Write(result, 0, received);
writer.Flush();
receive += (long)received;
}
writer.Flush();
writer.Close();
ServerManager.Instance.FileList.Add(new ServerManager.FileInfomation(fileName, (length / 1024).ToString()));
Debug.Log(fileName + " Receive Finish");
// LoadImage.instance.LoadTexture(Path.Combine(ServerManager.Instance.savePath, fileName));
ServerManager.Instance.AddMessage(fileName + " Receive Finish");
Main.instance.message = "上传";
}
static void SendFile(string request, Socket clientSocket)
{
string[] command = request.Split(',');
string requestName = command[1].Substring(0, int.Parse(command[2]));
string path = Path.Combine(ServerManager.Instance.savePath, command[1].Substring(0, int.Parse(command[2])));
FileStream reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None);
long send = 0L, length = reader.Length;
string fileName = requestName;
string sendStr = "Sending File," + fileName + "," + length.ToString();
Debug.Log(sendStr);
ServerManager.Instance.AddMessage(sendStr);
clientSocket.Send(EncoderToByte(sendStr));
int BufferSize = 1024;
byte[] buffer = new byte[1024];
clientSocket.Receive(buffer);
string message = DecoderToString(buffer);
Debug.Log(message);
if (message.Contains("Ready for sending"))
{
ServerManager.Instance.AddMessage("Sending File:" + fileName + ".Plz wait...");
Debug.Log("Sending File:" + fileName + ".Plz wait...");
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");
ServerManager.Instance.AddMessage(fileName + " Send Finish");
}
else
{
Debug.Log(message);
}
reader.Flush();
reader.Close();
return;
}
static void CloseSocket(Socket socket)
{
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 string ListToString(List<ServerManager.FileInfomation> list)
{
string str = "";
foreach (var fileInfo in list)
{
str += fileInfo.fileName;
str += ",";
str += fileInfo.fileSize;
str += ",";
}
return str;
}
}
}
欢迎讨论Q 1390659165