bool isServer = false; //该程序是否是服务器
bool isText = true; //允许发送消息
bool isSend = false; //正在发送
bool isRec = false; //正在接收
const string Txt = "8"; //文本消息
const string Request="0"; //发送端请求
const string Ready="3"; //发送端发送数据就绪信号(发送该信号后即开始传送文件)
const string NextWillData="4";
const string Data="5";
const string Accept="1"; //接收端接受数据
const string DataRefuse="2"; //接收端拒绝
const string DataEnd="6"; //接收端发送完成标志
const string DataAbort = "7"; //终止传输
public void ServerOrClientFun(TcpClient client)
{
if (isText)
{
string ReceiveMsg = SocketHelper.GetMsg(client);
if (isSend){ //如果isSend,则将消息转给SendFun
SendMsgStr = ReceiveMsg;
}
if (ReceiveMsg != "")
{
switch (ReceiveMsg[0].ToString()) //握手
{
case Request:
AddMsg("文件请求");
if (MessageBox.Show("请接收文件!", "文件接收", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
RecCount = 0;
FileName = ReceiveMsg.Substring(1);
SaveFileDialog s = new SaveFileDialog();
s.FileName = FileName;
if (s.ShowDialog() == DialogResult.OK)
{
fileStream = new FileStream(s.FileName, FileMode.Create, FileAccess.Write);
SocketHelper.SendMsg(client, Accept);
}
else
{
SocketHelper.SendMsg(client, DataRefuse);
}
}
else
{
SocketHelper.SendMsg(client, DataRefuse);
}
break;
case Ready:
AddMsg("发送端已就绪");
SocketHelper.SendMsg(client, NextWillData);
break;
case NextWillData:
AddMsg("NextWillData");
if (!isSend)
{
isText = false;
SocketHelper.SendMsg(client, Data);
}
else {
SocketHelper.SendMsg(client, NextWillData);
}
break;
case DataEnd:
if (!isSend)
{
AddMsg("接收完成!DataEnd");
MessageBox.Show("接收完成!");
}
else {
SocketHelper.SendMsg(client, DataEnd); //接收到接收端发来的接收完成信息然后向接收端发送文件接收完成的信息
AddMsg("发送完成!DataEnd");
MessageBox.Show("发送完成!");
}
FreeResource();
break;
case DataAbort:
FreeResource();
AddMsg("传输已终止");
MessageBox.Show("传输已终止!");
break;
case Txt:
AddMsg(SocketHelper.GetRemoteAddress(client) + ":" + ReceiveMsg.Substring(1));
break;
case Accept:
AddMsg("接收端接收请求");
fileStream = new FileStream(FileName, FileMode.Open, FileAccess.Read);
SocketHelper.SendMsg(client, Ready);
break;
case DataRefuse:
AddMsg("接收端拒绝请求");
FreeResource();
MessageBox.Show("对方已拒绝!");
break;
case Data:
AddMsg("Data正在发送数据");
byte[] bt = new byte[BlockLen];
int ReadLen = fileStream.Read(bt, 0, BlockLen);
SocketHelper.SendBuffer(client, bt, ReadLen);
break;
}
}
}
else
{ //接收文件
NetworkStream sr = client.GetStream();
if (sr.CanRead)
{
byte[] bt = new byte[BlockLen];
int ReadLen = sr.Read(bt, 0, bt.Length);
fileStream.Write(bt, 0, ReadLen);
isText = true;
if (ReadLen < BlockLen)
{
fileStream.Flush();
fileStream.Close();
SocketHelper.SendMsg(client, DataEnd);
}
else
{
SocketHelper.SendMsg(client, NextWillData);
}
}
RecCount++;
SetStatus("数据接收次数:" + RecCount);
}
}