Unity C# TCP通信与大文件传输
Sever:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Windows.Forms;
namespace SocketServer
{
class Program
{
public static string serverIp = "127.0.0.1";//设置服务端IP
public static int serverPort = 8888;//服务端端口
[STAThread]
static void Main(string[] args)
{
//string path= @"..\ipconfig.txt";
//string[] strs = File.ReadAllLines(path);//将filename路径的txt读取为string数组
// Console.WriteLine(strs[0]);
//serverIp = strs[0];//设置服务端IP
//serverPort =int .Parse ( strs[1]);//服务端端口
SocketServer();
}
public static Socket socketServer;//定义socket
public static Thread threadWatch;//定义线程
public static byte[] result = new byte[1024 * 1024 * 2];//定义缓存
//public static string fileName;//获取文件名
public static string filePath = "";//存储保存文件的路径
public static void SocketServer()
{
socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个socket的对象
IPAddress ip = IPAddress.Parse(serverIp);//获取服务器IP地址
IPEndPoint point = new IPEndPoint(ip, serverPort);//获取端口
try
{
socketServer.Bind(point);//绑定IP地址及端口
}
catch (Exception ex)
{
Console.WriteLine("绑定IP时出现异常:" + ex.Message);
return;
}
socketServer.Listen(100);//开启监听并设定最多10个排队连接请求
threadWatch = new Thread(WatchConnect);//创建一个监听进程
threadWatch.IsBackground = true;//后台启动
threadWatch.Start();//运行
Console.WriteLine("服务器{0}监听启动成功!", socketServer.LocalEndPoint.ToString());
Console.ReadLine();
}
public static void WatchConnect()
{
while (true)
{
Socket watchConnect = socketServer.Accept();//接收连接并返回一个新的Socket
watchConnect.Send(Encoding.UTF8.GetBytes("服务器连接成功"));//在客户端显示"服务器连接成功"提示
Thread threadwhat = new Thread(ReceiveMsg);//创建一个接受信息的进程
threadwhat.IsBackground = true;//后台启动
threadwhat.Start(watchConnect);//有传入参数的线程
}
}
public static DateTime GetTime()
{
DateTime now = new DateTime();
now = DateTime.Now;
return now;
}
public static void showproc(string headstr, float proc)
{
string a = headstr;
for (int i = 1; i <= (10 - proc.ToString().Length); i+