Thread threadWatch = null;
Socket listen = null;
/// <summary>
/// 服务端监听请求
/// </summary>
private void bt_beginListen_Click(object sender, EventArgs e)
{
listen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(tb_ip.Text.Trim());
IPEndPoint ipport = new IPEndPoint(ip, int.Parse(tb_port.Text.Trim()));
listen.Bind(ipport);
listen.Listen(10);
threadWatch = new Thread(watchConnection);
threadWatch.IsBackground = true;
threadWatch.Start();
tb_msg.Text = "服务端启动监听!";
}
//保存服务端和所有客户端通信的socket
Dictionary<string, Socket> dict = new Dictionary<string, Socket>();
//保存服务端 所有调用socket.Receive方法的线程
Dictionary<string, Thread> dictThread = new Dictionary<string, Thread>();
/// <summary>
/// 监听客户端请求的方法
/// </summary>
void watchConnection()
{
while (true)
{
Socket connection = listen.Accept();
//将客户端的IP和端口保存起来
dict.Add(connection.RemoteEndPoint.ToString(), connection);
//在在线客户端列表区显示其ip和port
listBox_online.Items.Add(connection.RemoteEndPoint.ToString());
//创建socket线程
Thread thread = new Thread(receiveMsg);
thread.IsBackground = true;
thread.ApartmentState = ApartmentState.STA;--加上此代码后问题解决
thread.Start(connection);
dictThread.Add(connection.RemoteEndPoint.ToString(), thread);
tb_msg.Text += "\r\n客户端连接成功!";
}
}
/// <summary>
/// 接受客户端数据的方法
/// </summary>
/// <param name="socketClient"></param>
void receiveMsg(object socketClient)
{
Socket socket_Client = socketClient as Socket;
while (true)
{
//定义接受数据的缓存区
byte[] arrMsgReceive = new byte[1024 * 1024 * 1];
//将接受到的数据存入缓存区,并返回数据的长度
int length = socket_Client.Receive(arrMsgReceive);
if (arrMsgReceive[0] == 0)//发送过来的数据时文字
{
string strMsgReceive = System.Text.Encoding.UTF8.GetString(arrMsgReceive, 0, length);
this.tb_msg.Text += strMsgReceive + "\r\n";
}
else if (arrMsgReceive[0] == 1)//发送过来的数据时文件
{
SaveFileDialog sfd = new SaveFileDialog();--此部出现问题 弹不出来
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string saveFilePath = sfd.FileName;
//将接受来的数据保存到本地
using (FileStream fs = new FileStream(saveFilePath, FileMode.Create, FileAccess.Write))
{
fs.Write(arrMsgReceive, 1, length - 1);
tb_msg.Text += "文件保存成功!保存路径:" + saveFilePath+"\r\n";
}
}
}
}
}
求解为什么保存对话框弹不出来? 问题二:加上代码thread.ApartmentState = ApartmentState.STA;是什么意思?
|