none
求助!!!!关于socket 异步通讯客户端问题 RRS feed

  • 问题



  • 以下是我的客户端代码。我根据MSDN上面的示例稍作修改 没有关闭通讯通道。问题出在第2次输入数据,在返回的时候 textBox1显示是第一次返回的数据,当第3次点击button的时候textBox1显示我第2次输入的数据,如果我在程序中StartClient()方法里面随意切一个断点,则没有任何问题,可能说的不太清楚 打个比方我第一次输入123 那么textBox1显示为服务器端返回的数据123,当我第2次输入456的时候 如果程序不切断点 则还是显示123 当我在输入678的时候 textBox1显示为456,如果我切一个断点 第2次输入 456的时候textBox1显示456,我个人怀疑是线程控制问题,但是我实在没找到 到底哪出了问题,请求各位帮忙,还有一个问题,现在这个编码个是两端输入中文传输以后显示的都是问号 如何修改才能显示中文呢。再次先谢谢各位了。麻烦各位帮忙看一下!!!!!我需要是客户端或者服务端手动关闭通道,不是通讯一次既关闭的那种,下次通讯在打开的那种。

     下面是我客户端代码:

    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.IO;
    
    using System.Net.Sockets;
    
    using System.Net;
    
    using System.Threading;
    
    
    
    namespace Client1
    
    {
    
     public partial class Form1 : Form
    
     {
    
      private static ManualResetEvent connectDone = new ManualResetEvent(false);
    
      private static ManualResetEvent sendDone = new ManualResetEvent(false);
    
      private static ManualResetEvent receiveDone = new ManualResetEvent(false);
    
      private static String str = String.Empty;
    
      private static Socket qclient = null;
    
      private static IPHostEntry ipHostentry = null;
    
      private static IPAddress ipAdderss = null;
    
      private static IPEndPoint remip = null;
    
      private static bool connectboll = true;
    
      public class StateObject
    
      {
    
       public Socket workSocket = null;
    
       public const int BufferSize = 256;
    
       public byte[] buffer = new byte[BufferSize];
    
       public StringBuilder sb = new StringBuilder();
    
      }
    
      public Form1()
    
      {
    
       InitializeComponent();
    
      }
    
    
    
      private void Form1_Load(object sender, EventArgs e)
    
      {
    
    
    
    
    
    
    
      }
    
    
    
      private void button1_Click(object sender, EventArgs e)
    
      {
    
       StartClient(this.textBox2.Text.ToString().Trim());
    
       if (qclient.Connected)
    
       {
    
        connectboll = false;
    
       }
    
       this.textBox1.Text = str.ToString();
    
      }
    
      public static void StartClient(string strsend)
    
      {
    
       try
    
       {
    
        if (connectboll)
    
        {
    
         ipHostentry = Dns.Resolve("192.168.0.102");
    
         ipAdderss = ipHostentry.AddressList[0];
    
         remip = new IPEndPoint(ipAdderss, 8001);
    
         qclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    
         qclient.BeginConnect(remip, new AsyncCallback(ConnectCallback), qclient);
    
         connectDone.WaitOne();
    
    
    
        }
    
        Send(qclient, strsend);
    
        sendDone.WaitOne();
    
        Receive(qclient);
    
        receiveDone.WaitOne();
    
        
    
        //qclient.Shutdown(SocketShutdown.Both);
    
        // client.Close();
    
       }
    
       catch (Exception ex)
    
       {
    
       }
    
      }
    
      public static void ConnectCallback(IAsyncResult ar)
    
      {
    
       try
    
       {
    
        Socket client = (Socket)ar.AsyncState;
    
        client.EndConnect(ar);
    
        connectDone.Set();
    
       }
    
       catch (Exception ex)
    
       {
    
       }
    
      }
    
      public static void Send(Socket client, String data)
    
      {
    
       byte[] byteData = Encoding.ASCII.GetBytes(data);
    
       client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client);
    
    
    
      }
    
      public static void SendCallback(IAsyncResult ar)
    
      {
    
       try
    
       {
    
        Socket client = (Socket)ar.AsyncState;
    
        int bytesSent = client.EndSend(ar);
    
        sendDone.Set();
    
       }
    
       catch (Exception e)
    
       {
    
        Console.WriteLine(e.ToString());
    
       }
    
    
    
      }
    
      public static void Receive(Socket client)
    
      {
    
       try
    
       {
    
        StateObject state = new StateObject();
    
        state.workSocket = client;
    
        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
    
       }
    
       catch (Exception ex)
    
       {
    
       }
    
      }
    
      public static void ReceiveCallback(IAsyncResult ar)
    
      {
    
       try
    
       {
    
        StateObject state = (StateObject)ar.AsyncState;
    
        Socket client = state.workSocket;
    
        int i = client.EndReceive(ar);
    
        if (i > 0)
    
        {
    
         state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, i));
    
         client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
    
         str = state.sb.ToString();
    
         state.sb = new StringBuilder();
    
         receiveDone.Set();
    
    
    
        }
    
        else
    
        {
    
         if (state.sb.Length > 0)
    
         {
    
          str = state.sb.ToString();
    
         }
    
         // receiveDone.Set();
    
    
    
        }
    
       }
    
       catch (Exception ex)
    
       {
    
       }
    
      }
    
     }
    
    }
    
    
    
    


     

     

    下面是我服务器端代码。

    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.IO;
    using System.Threading;

    namespace Server1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            private static string strmessage;
            public static ManualResetEvent alldone = new ManualResetEvent(false);
            private void Form1_Load(object sender, EventArgs e)
            {

            }

            private void button1_Click(object sender, EventArgs e)
            {
                StarListing();

                //this.textBox1.Text = strmessage;

            }
            public class StateObject
            {
                public Socket workSocket = null;
                public const int BufferSize = 1024;
                public byte[] buffer = new byte[BufferSize];
                public StringBuilder sb = new StringBuilder();
            }

            public static void StarListing()
            {
                Byte[] byetes = new Byte[1024];
                IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                IPAddress ipaddress = ipHostInfo.AddressList[0];
                IPEndPoint ipendpoint = new IPEndPoint(ipaddress, 8001);
                Socket listsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    listsocket.Bind(ipendpoint);
                    listsocket.Listen(100);
                    while (true)
                    {
                        alldone.Reset();
                        listsocket.BeginAccept(new AsyncCallback(AcceptCallback), listsocket);
                        alldone.WaitOne();
                    }
                }
                catch (Exception ex)
                {
                }
            }

            public static void AcceptCallback(IAsyncResult ar)
            {
                alldone.Set();
                Socket listtener = (Socket)ar.AsyncState;
                Socket handler = listtener.EndAccept(ar);
                StateObject stateobject = new StateObject();
                stateobject.workSocket = handler;
                handler.BeginReceive(stateobject.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), stateobject);

            }
            public static void ReadCallback(IAsyncResult ar)
            {
                Socket hadler = null;
                try
                {
                    String str = String.Empty;
                    StateObject state = (StateObject)ar.AsyncState;
                    hadler = state.workSocket;
                    int i = hadler.EndReceive(ar);
                    if (i > 0)
                    {
                        state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, i));
                        str = state.sb.ToString();
                            Send(hadler, str + "服务器");
                            hadler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                            state.sb = new StringBuilder();                }
                }
                catch (Exception ex)
                {
                    hadler.Shutdown(SocketShutdown.Both);
                    hadler.Close();
                }
            }
            public static void Send(Socket hadler, String str)
            {
                byte[] bytedate = Encoding.ASCII.GetBytes(str);
                hadler.BeginSend(bytedate, 0, bytedate.Length, 0, new AsyncCallback(SendCallback), hadler);
            }
            public static void SendCallback(IAsyncResult ar)
            {
                try
                {
                    Socket hadler = (Socket)ar.AsyncState;
                    int bytessend = hadler.EndSend(ar);
                   
                    //hadler.Shutdown(SocketShutdown.Both);
                    //hadler.Close();
                }
                catch (Exception ex)
                {
                }
            }

        }
    }

     






    2011年7月2日 18:20

全部回复