初学c#,我想用c#写个聊天的程序,再网上看了些代码,自己写的时候发现很多问题。
我在运行的时候第一个客户端与服务端能正常发送消息,但使用第二个客户端的时候,第一个客户端与服务端的连接又中断了,始终只能有一个客服端与服务端连接不能多客户端与服务器连接。希望各位帮我看下代码问题。

解决方案 »

  1.   

    服务端代码:
    public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            private void Form1_Load(object sender, EventArgs e)
            {
            }
            IPAddress HostIP = IPAddress.Parse("127.0.0.1");
            bool flag = true;
            Socket acceptedSocket;
            #region//进程方法
            private void Proccess()
            {
                    while (flag)
                    {
                        byte[] receiveByte = new byte[64];
                        acceptedSocket.Receive(receiveByte, receiveByte.Length, 0);
                       string strInfo = Encoding.BigEndianUnicode.GetString(receiveByte);
                        Byte[] sendByte = new Byte[64];
                        string sendStr = strInfo;
                        sendByte = Encoding.BigEndianUnicode.GetBytes(sendStr.ToCharArray());
                        acceptedSocket.Send(sendByte, sendByte.Length, 0);
                    }
            }
            #endregion        private void button3_Click(object sender, EventArgs e)
            {
                acceptedSocket.Close();
            }
            private void startlisten()
            {
                TcpListener listener = new TcpListener(HostIP, Int32.Parse("11000"));
                listener.Start();
                 while (true)
                 {          
                    try
                    {
                        acceptedSocket = listener.AcceptSocket();
                        Thread thread = new Thread(new ThreadStart(Proccess));
                        thread.Start();
                    }
                    catch (Exception ey)
                    {
                        MessageBox.Show(ey.Message);
                    }
                 }
            }        private void button1_Click_1(object sender, EventArgs e)
            {
                Thread newthread = new Thread(new ThreadStart(startlisten));
                newthread.Start();
            }    }
      

  2.   

    客户端代码:namespace win_talkClient
    {
        public partial class Form1 : Form
        {
            #region//声名变量
            IPAddress HostIP = IPAddress.Parse("127.0.0.1");
            IPEndPoint point;
            Socket socket;
            bool flag = true;
            #endregion              #region//声名委托
            delegate void SetTextCallback(string text);
            private void SetText(string text)
            {
               textBox2.AppendText(text+"\r\n");
           }
            #endregion       #region//进程
           private void Proccess()
            {
                    while (flag)
                    {
                        byte[] receiveByte = new byte[64];
                        socket.Receive(receiveByte, receiveByte.Length, 0);
                        string strInfo = Encoding.BigEndianUnicode.GetString(receiveByte);
                        this.Invoke(new SetTextCallback(SetText),new object[]{strInfo});
                        
                    }
            }
           #endregion        private void button2_Click(object sender, EventArgs e)
            {
                try
                {
                    Byte[] sendByte = new Byte[64];
                    string sendStr = this.textBox1.Text + ":" + this.textBox3.Text+"\r\n";
                    sendByte = Encoding.BigEndianUnicode.GetBytes(sendStr.ToCharArray());
                    socket.Send(sendByte, sendByte.Length, 0);
                }
                catch { }
            }
            
            public Form1()
                {
                    InitializeComponent();
                }        private void Form1_Load(object sender, EventArgs e)
                {            }         private void button1_Click(object sender, EventArgs e)
                {
                        try
                        {
                            point = new IPEndPoint(HostIP, Int32.Parse("11000"));
                            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                            socket.Connect(point);
                            Thread thread = new Thread(new ThreadStart(Proccess));
                            thread.Start();
                        }
                        catch (Exception ey)
                        {
                            MessageBox.Show("服务器进程没有开启\r\n" + ey.Message);
                        }
                }        private void button3_Click(object sender, EventArgs e)
            {
                socket.Close();
            }
        }
    }
      

  3.   

    没有细看。
    1、确认是否是长连接的,还是发送一次就断开。
    2、是否客户端都在同一台电脑上,同一PC上,同一端口只能提供给同一个客户端。回答问题要查资料?用《Csdn收音机》可以最快速度搞定!
      

  4.   

    你把Socket acceptedSocket;
    定义为全局变量,当第二个连接的时候,这个变量就是第二个了,第一个已经被释放了。
    那是当然的。改为局部变量,或变量列表吧。
      

  5.   

    我也遇到的,刚刚解决。
    把服务器端接收到的客户端套接字保存到一个List中,然后为每个客户端套接字创建一个线程。我在你的代码上修改下吧。 private List<Socket> ClientList=new List<Socket>();//这个初始化你看你在构造函数中吧
     private void startlisten()//服务器端的监听函数
      {
      TcpListener listener = new TcpListener(HostIP, Int32.Parse("11000"));
      listener.Start();
      while (true)
      {   
      try
      {
      acceptedSocket = listener.AcceptSocket();
      ClientList.Add(acceptedSocket);//添加进接收到的客户端集合中
      Thread thread = new Thread(new ParameterizedThreadStart(Proccess));
      thread.Start(ClientList.Count-1);//表示为当前接收到的连接创建处理线程
      }
      catch (Exception ey)
      {
      MessageBox.Show(ey.Message);
      }
      }
      } #region//进程方法
      private void Proccess(object index)//这里确保为每个客户端连接创建了一个线程
      {
    int i=(int)index;
      while (flag)
      {
      byte[] receiveByte = new byte[64];
      //把之前的acceptedSocket 换为ClientList[i]
      ClientList[i].Receive(receiveByte, receiveByte.Length, 0);
      string strInfo = Encoding.BigEndianUnicode.GetString(receiveByte);
      Byte[] sendByte = new Byte[64];
      string sendStr = strInfo;
      sendByte = Encoding.BigEndianUnicode.GetBytes(sendStr.ToCharArray());
      //把之前的acceptedSocket 换为ClientList[i]
       ClientList[i].Send(sendByte, sendByte.Length, 0);
      }
      }
      #endregion
    原来在Process中使用acceptedSocket,因为acceptedSocket表示每次接收到的最新的客户端的连接,所以服务器每次只能接收到最后一次连接到的客户端信息。
      

  6.   

    可以啊 发送消息的时候对ClientList中接受到的客户端每个都发送消息也可以呀