2013-06-10 2 views
1

내 소켓이 다른 부분에서받은 데이터를 표시하고 있습니다. 예를 들어 로그인 할 때 제대로 작동하지만 서버에서 채팅 메시지를 보내면 로그인에서 보낸 사용자 이름이 표시됩니다. 여기소켓에 이전 데이터가 표시되는 이유

using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Text; 
    using System.Threading.Tasks; 
    using System.Net.Sockets; 
    using System.Net; 
    using System.Threading; 
    using System.Windows.Forms; 
    using System.IO; 

    namespace Banshee_Server 
    { 
     class Network 
     { 
      public Socket listener; 
      IPEndPoint localEndPoint; 
      public const int BufferSize = 1024; 
      public byte[] buffer = new byte[BufferSize]; 

      public static Dictionary<Socket, Player> dictionary = new Dictionary<Socket, Player>(); 

      public Player getPlayer(Socket socket) 
      { 
       if (socket != null) 
       { 
        if(dictionary.ContainsKey(socket)) 
        { 
         return dictionary[socket]; 
        } 
        else 
        { 
         return null; 
        } 
       } 
       else 
       { 
        return null; 
       } 
      } 

      public bool playerIsLoggedIn(String player) 
      { 
       try 
       { 
        foreach (Socket sock in dictionary.Keys) 
        { 
         if (getPlayer(sock).Name.ToLower() == player.ToLower()) 
         { 
          return true; 
         } 
        } 
        return false; 
       } 
       catch { 
        return true; 
       } 
      } 

      public static int getFreePlayerIndex 
      { 
       get { return Network.dictionary.Count(); } 
      } 

      netHandler handlers = new netHandler(); 

      public Network(Socket socket, int port) 
      { 
       this.listener = socket; 
       localEndPoint = new IPEndPoint(IPAddress.Loopback, port); 
      } 

      public void bindListener() 
      { 
       listener.Bind(localEndPoint); 
      } 
      public void startListening() 
      { 

       try 
       { 

        listener.Listen(100); 
        listener.BeginAccept(new AsyncCallback(AcceptCallback), listener); 
       } 
       catch (Exception e) 
       { 
        MessageBox.Show(e.ToString()); 
       } 
      } 

      public void AcceptCallback(IAsyncResult ar){ 
       Socket listener = (Socket)ar.AsyncState; 
       Socket handler = listener.EndAccept(ar); 
       startListening(); 
       handler.BeginReceive(buffer, 0, BufferSize, 0, new AsyncCallback(ReadCallback), handler); 
       Common common = new Common(); 
       common.appendLog("New Connection received from " + handler.RemoteEndPoint.ToString()); 

      } 

      public void ReadCallback(IAsyncResult ar){ 
       Socket handler = (Socket)ar.AsyncState; 
       try 
       { 
        int bytesRead = handler.EndReceive(ar); 

        if (bytesRead > 0) 
        { 
         StringBuilder sb = new StringBuilder(); 
         byte[] byteData = new byte[bytesRead]; 
         byteData = buffer; 
         byte[] readData = new byte[byteData.Length - 1]; 
         Buffer.BlockCopy(byteData, 1, readData, 0, readData.Length); 
         sb.Append(Encoding.ASCII.GetString(readData)); 
         String data = sb.ToString(); 



         handlers.handleData(handlers.getHandlerType(byteData[0]), data, handler); 

         handler.BeginReceive(buffer, 0, BufferSize, 0, new AsyncCallback(ReadCallback), handler); 
        } 
        else 
        { 
         handler.BeginReceive(buffer, 0, BufferSize, 0, new AsyncCallback(ReadCallback), handler); 
        } 
       } 
       catch 
       { 

       } 

      } 

      private static void sendFileCallback(IAsyncResult ar) 
      { 
       Socket client = (Socket)ar.AsyncState; 

       client.EndSendFile(ar); 
      } 

      public void Send(Socket sock, String data, byte dataType) 
      { 
       byte[] byteType = new byte[1]; 
       byteType[0] = dataType; 

       int bufferSize = byteType.Length + Encoding.ASCII.GetBytes(data).Length; 
       var ms = new MemoryStream(new byte[bufferSize], 0, bufferSize, true, true); 
       ms.Write(byteType, 0, byteType.Length); 
       ms.Write(Encoding.ASCII.GetBytes(data), 0, Encoding.ASCII.GetBytes(data).Length); 

       byte[] byteData = ms.GetBuffer(); 

       sock.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), sock); 
      } 

      public void SendtoAll(String data, byte dataType) 
      { 

       try 
       { 
        foreach (Socket sock in dictionary.Keys) 
        { 
         try 
         { 
          Send(sock, data, dataType); 
         } 
         catch 
         { 
          handlers.logoutPlayer(sock, this); 
         } 
        } 
       } 
       catch { } 
      } 


      private static void SendCallback(IAsyncResult ar) 
      { 
       try 
       { 

        Socket handler = (Socket)ar.AsyncState; 
        int bytesSent = handler.EndSend(ar); 
       } 
       catch (Exception e) 
       { 
        MessageBox.Show(e.ToString()); 
       } 
      } 

     } 
    } 

그리고 클라이언트에서 네트워크 클래스입니다 : 여기

서버에서 네트워크 클래스입니다

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Net; 
using System.Net.Sockets; 
using System.Windows.Forms; 
using System.IO; 
using System.Threading; 

namespace Ghoul_Engine 
{ 
    class network 
    { 

     public Socket sock; 
     public const int BufferSize = 1024; 
     public Byte[] buffer = new Byte[BufferSize]; 
     public IPEndPoint RemoteEndPoint; 



     public network() 
     { 


     } 

     public void beginConnect(Socket socket) 
     { 
      sock = socket; 
      try 
      { 
       sock.BeginConnect(RemoteEndPoint, new AsyncCallback(onConnect), sock); 
      } 
      catch 
      { 
       MessageBox.Show("Could not connect to remote server. Perhaps it's down."); 
      } 
     } 

     public void onConnect(IAsyncResult ar) 
     { 
      try 
      { 
       sock.EndConnect(ar); 
       sock.BeginReceive(buffer, 0, BufferSize, 0, new AsyncCallback(ReadCallback), sock); 
      } catch{ 
       MessageBox.Show("Error connecting to server, it could be down!"); 
      } 
     } 

     public void ReadCallback(IAsyncResult ar) 
     { 
      Socket sock = (Socket)ar.AsyncState; 
      try 
      { 
       int bytesRead = sock.EndReceive(ar); 

      if (bytesRead > 0) 
      { 

       StringBuilder sb = new StringBuilder(); 
       byte[] byteData = new byte[bytesRead]; 
       byteData = buffer; 
       byte[] readData = new byte[byteData.Length - 1]; 
       Buffer.BlockCopy(byteData, 1, readData, 0, readData.Length); 
       sb.Append(Encoding.ASCII.GetString(readData)); 
       String data = sb.ToString(); 



       Program.netHandlers.handleData(Program.netHandlers.getHandlerType(byteData[0]), data, sock); 
       if(sock.Connected){ 
        sock.BeginReceive(buffer, 0, BufferSize, 0, new AsyncCallback(ReadCallback), sock); 
       } 
      } 
      else 
      { 
       if(sock.Connected){ 
        sock.BeginReceive(buffer, 0, BufferSize, 0, new AsyncCallback(ReadCallback), sock); 
       } 

      } 
      } 
      catch { } 

     } 



     public void Send(String data, byte dataType) 
     { 
      byte[] byteType = new byte[1]; 
      byteType[0] = dataType; 

      int bufferSize = byteType.Length + Encoding.ASCII.GetBytes(data).Length; 
      var ms = new MemoryStream(new byte[bufferSize], 0, bufferSize, true, true); 
      ms.Write(byteType, 0, byteType.Length); 
      ms.Write(Encoding.ASCII.GetBytes(data), 0, Encoding.ASCII.GetBytes(data).Length); 

      byte[] byteData = ms.GetBuffer(); 

      sock.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), sock); 
     } 

     private static void SendCallback(IAsyncResult ar) 
     { 
      try 
      { 
       Socket handler = (Socket)ar.AsyncState; 
       int bytesSent = handler.EndSend(ar); 
      } 
      catch (Exception e) 
      { 
       MessageBox.Show(e.ToString()); 
      } 
     } 
     public void closeSocket() 
     { 
      try 
      { 
       if (sock.Connected) 
       { 
        sock.Close(); 
       } 
      } 
      catch { } 
     } 

     public Socket getSocket() 
     { 
      return sock; 
     } 
    } 
} 

어떤 아이디어가? 여기에 코드의

+0

코드가 너무 많습니다. [단축, 자체 포함, 편집 가능한 예] (http://sscce.org/)로 줄이십시오. –

+0

음, 코드가 너무 많습니다. F11을 사용하여 데이터를 디버그하고 따라 해 보았습니까? – Andrew

답변

0

귀하의 큰 덩어리 :

 StringBuilder sb = new StringBuilder(); 
     byte[] byteData = new byte[bytesRead]; 
     byteData = buffer; 
     byte[] readData = new byte[byteData.Length - 1]; 
     Buffer.BlockCopy(byteData, 1, readData, 0, readData.Length); 
     sb.Append(Encoding.ASCII.GetString(readData)); 
     String data = sb.ToString(); 

간단하게 교체 할 수 있습니다 :

 String data = Encoding.ASCII.GetString(buffer, 0, bytesRead); 

문제에 관해서는, 나는 당신이 게시 코드에 명백한 아무것도 표시되지 않습니다. 문제는 handleData() 메소드에있을 수 있습니다.

+0

나는 내가 테스트하려고하는 이론을 가지고있다. 그것은 buffer []의 바이트가 null로 되돌아 가지 않는 것과 관련이 있다고 생각한다. –

+0

제 이론이 효과가있었습니다. 당신을 도와 줘서 고마워. :) –

+0

'bytesRead '가 얼마나 많은 양의'buffer'가 유효한 데이터를 가지고 있는지 알려줄 것이기 때문에 중요하지 않습니다. 다른 버퍼에 대해 말하지 않는 한? –

2

서버에는 사용자의 Network 클래스 구성원이 있지만 각 클라이언트에 대해 동시에 여러 실행 경로가 있습니다. 모든 클라이언트에 대해이 동일한 버퍼를 사용하려고하면 이러한 충돌이 발생합니다.

공유 버퍼를 사용하지 말고 각 메시지마다 별도의 버퍼를 사용하는 것이 좋습니다.

관련 문제