用socket编程做个简单的通讯,传送文件时候客户端弹不出文件打开对话框.这是什么回事?
客户端代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;namespace MyChatSoftClient
{
    public partial class Clientfrm : Form
    {
        public Clientfrm()
        {
            InitializeComponent();
            TextBox.CheckForIllegalCrossThreadCalls = false;
        }        #region 错误消息
        public void ShowErro(string msg, Exception ex)
        {
            ShowMsg("=======begin========");
            ShowMsg(msg + ex.Message);
            ShowMsg("=======end=========");
        } 
        
        public void ShowMsg(string msg)
        {
            txtShow.AppendText(msg + "\r\n");
        } 
        #endregion
        Socket sockCleint = null;
        Thread threadClient = null;        private void btnConnect_Click(object sender, EventArgs e)
        {
            Connecting();
        }
        private void Connecting()
        {
            try 
          {         
        sockCleint = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ipaddres = IPAddress.Parse(txtIPAddress.Text.Trim());
                IPEndPoint endpoint=new IPEndPoint(ipaddres,int.Parse(txtPort.Text.Trim()));
                sockCleint.Connect(endpoint);
                threadClient = new Thread(ReciveMsg);
                
                threadClient.Start();
            }
        catch (Exception ex)
        {
                ShowErro("",ex);

        }
        }        private void ReciveMsg()
        {
            while (true)
            {
                try
                {
                    byte[] byteMsg = new byte[1024 * 1024 * 4];
                    int length = sockCleint.Receive(byteMsg);
                    //接收到数据了
                    if (length > 0)
                    {
                        //接收的是字符串
                        if (byteMsg[0] == 0)
                        {
                            
                         //string strMsg = Encoding.UTF8.GetString(byteMsg, 0, length);
                            string strMsg = Encoding.UTF8.GetString(byteMsg,1, length);
                            ShowMsg(strMsg);
                        }
                            //接收的是文件
                        else if(byteMsg[0]==1)
                        {
                            try
                            {
                                OpenFileDialog ofd = new OpenFileDialog();
                                ofd.InitialDirectory = @"F:\";
                                if (ofd.ShowDialog() == DialogResult.OK)
                                {
                                    string savePath = ofd.FileName;
                                    FileStream fs = new FileStream(savePath, FileMode.Create);
                                    fs.Write(byteMsg, 1, byteMsg.Length - 1);
                                    ShowMsg("保存完毕!"+savePath);
                                }
                            }
                            catch (Exception ex)
                            {                                ShowErro("",ex);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {                    ShowErro("",ex);
                    break;
                }
            }
        }        private void Clientfrm_Load(object sender, EventArgs e)
        {        }        private void btnSend_Click(object sender, EventArgs e)
        {
            string strMsg = txtShendMsg.Text.Trim();
            byte[] byteSend = Encoding.UTF8.GetBytes(strMsg);
            sockCleint.Send(byteSend);
        }        private void Clientfrm_FormClosing(object sender, FormClosingEventArgs e)
        {        }
    }
}服务端:using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;namespace MyChatShort
{
    public partial class ServerFrm : Form
    {
        public ServerFrm()
        {
            InitializeComponent();
            TextBox.CheckForIllegalCrossThreadCalls = false;
        }
        public void ShowErro(string msg, Exception ex)
        {
            ShowMsg("=======begin========");
            ShowMsg(msg+ex.Message);
            ShowMsg("=======end=========");
        }
        public void ShowMsg(string msg)
        {
            txtShow.AppendText(msg+"\r\n");
        }        
        private void btnConnect_Click(object sender, EventArgs e)
        {
            
            StartListening();
        }
        Socket soketWelcomne = null;
        Socket soketConnection = null;
        Thread threadWatchPort = null;
        Thread threadRece = null;        public void StartListening()
        {
            try 
{         
//IP地址
            IPAddress address = IPAddress.Parse(txtIPAdress.Text.Trim());
            //IP节点和端口
            IPEndPoint endpoint=new IPEndPoint(address,int.Parse(txtPort.Text.Trim()));
            //创建监听套接字(寻址协议,流方式,TCP协议)
            soketWelcomne = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            soketWelcomne.Bind(endpoint);//套接字绑定在端口上面            soketWelcomne.Listen(10);//同时能处理的连接数
            
            threadWatchPort = new Thread(WatchPort);
            threadWatchPort.IsBackground = true;
            threadWatchPort.Start();
            
            ShowMsg("........监听开始......");
            
            
}
catch (Exception ex)
{        ShowErro("", ex);
}
        }
        public void WatchPort()
        {
            while (true)
            {
                try
                {
                    soketConnection = soketWelcomne.Accept();
                    ShowMsg("监听到连接");
                    threadRece = new Thread(Recever);
                    threadRece.IsBackground = true;
                    threadRece.Start();
                }
                catch (Exception ex)
                {                    ShowErro("",ex);
                }
                break;
                
            }
        }        private void btnSend_Click(object sender, EventArgs e)
        {
            string strMsg = SendMsg.Text.Trim();
            byte[] byteMsg = Encoding.UTF8.GetBytes(strMsg);
            //增加标识,
            byte[] byteFinalMsg = new byte[byteMsg.Length + 1];
            byteFinalMsg[0] = 0;
            Buffer.BlockCopy(byteMsg, 0, byteFinalMsg, 1, byteMsg.Length);            soketConnection.Send(byteFinalMsg, byteFinalMsg.Length, SocketFlags.None);
        }        private void Recever()
        {
            while (true)
            {
                try
                {
                    byte[] byteMsg = new byte[1024 * 1024 * 2];
                    int length = soketConnection.Receive(byteMsg, SocketFlags.None);
                    string strReceMsg = Encoding.UTF8.GetString(byteMsg, 0, length);
                    ShowMsg(strReceMsg);
                }
                catch (Exception ex)
                {                    ShowErro("", ex);
                } 
            }        }        private void btnChooseFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                txtToSendFilePath.Text = ofd.FileName;
            }        }        private void btnSendFile_Click(object sender, EventArgs e)
        {
            using (FileStream fs = new FileStream(txtToSendFilePath.Text, FileMode.Open))
            {
                byte[] byteFile=new byte[1024*1024*5];
                int length=fs.Read(byteFile, 0, byteFile.Length);
                if (length > 0)
                {
                    byte[] byteFinalFile = new byte[length + 1];
                    byteFinalFile[0] = 1;
                    Buffer.BlockCopy(byteFile, 0, byteFinalFile, 1, length);
                    soketConnection.Send(byteFinalFile);
                }
            }
        }
    }
}

解决方案 »

  1.   

    代码太长了,建议你先看看客户端收到了什么数据,看代码好像是监听线程阻塞导致的
    while(true)
    {
    soketConnection = soketWelcomne.Accept();
    ShowMsg("监听到连接");
    //将当前实例要传进去,否则一旦有并发连接,Recever还没处理完,soketConnection的引用就被更改,
    threadRece = new Thread(Recever, soketConnection);  
    threadRece.IsBackground = true;
    threadRece.Start();
    }
    Recever里面又是while(true),退出条件呢?private void Recever(Socket socket)
            {
                  var datas = new List<byte>(BUFFER_SIZE);
                  int offset = 0, available = socket.Available;          
                  var buffer = new byte[512];
                  try
                   {
                       while (datas.Count < available && (offset = socket.Receive(buffer)) > 0)
                       {                
                           var readData = buffer.Take(offset).ToArray();   //读取有效数据段                
                           datas.AddRange(readData);                       
                       }
                        string strReceMsg = Encoding.UTF8.GetString(datas.ToArray());
                        ShowMsg(strReceMsg);
                    }
                    catch (Exception ex)
                    { 
                        ShowErro("", ex);
                    } 
                }
     
            } 
      

  2.   

    建议你使用封装好的ReceiveAsync或者BeginReceive + EndReceive
      

  3.   

    你好,这个代码我在XP上运行时可以打开openfiledialog的.我的是win7 64位系统就是打不开.
      

  4.   

    问题解决了,TextBox.CheckForIllegalCrossThreadCalls = false; win7用这个不安全访问UI控件是不可行的,还是用委托传入OK了.比较麻烦