2011-11-13 2 views
0

이제 서버로 작업하려고합니다. 나는이 코드를 가지고있다 : enter image description here서버 연결 오류

'ParametrizedThreadStart'를 쓰레드에서 'HandleCC'메소드를 시작한다. 나는 '127.0.0.1'에서 연결을 시도하고있다. 나는 연결할 수있다. 연결되면 첫 번째 중단 점은 양호하지만 두 번째 중단 점은 코드 중단보다 좋습니다. (콘솔은 여전히 ​​실행 중이지만 다음 중단 점에서 아무도 코드를 깨지 않습니다.) 도움을 주셔서 감사합니다. 내 영어를 유감스럽게 생각합니다.

전체 코드 : 당신은 클라이언트와 서버를 모두 필요한 모든 클라이언트 - 서버 응용 프로그램에서

using System; 
using System.Text; 
using System.Net; 
using System.Net.Sockets; 
using System.IO; 
using System.Linq; 
using System.Collections.Generic; 
using System.Collections; 
using System.Threading; 
namespace MTSP 
{ 
class Comunication 
{ 
    private TcpListener listener; 
    private Thread thread; 
    public Comunication() 
    { 
     this.listener = new TcpListener(IPAddress.Any, 20345); 
     this.thread = new Thread(new ThreadStart(this.ListenLoop)); 
     this.thread.Start(); 
    } 
    private void ListenLoop() 
    { 
     this.listener.Start(); 
     while (true) 
     { 
      TcpClient client = this.listener.AcceptTcpClient(); 
      Thread tr = new Thread(new ParameterizedThreadStart(this.HandleCC)); 
      tr.Start(client); 
     } 
    } 
    private void HandleCC(object client) 
    { 
     TcpClient cli = (TcpClient)client; 
     NetworkStream stream = cli.GetStream(); 
     byte[] buffer = new byte[1024]; 
     int bytesread = 0; 
     string mess = ""; 
     StringBuilder compmess = new StringBuilder(); 
     while (true) 
     { 
      bytesread = 0; 
      try 
      { 
       bytesread = stream.Read(buffer, 0, buffer.Length); 
      } 
      catch 
      { 
       break; 
      } 

      compmess.AppendFormat("{0}", Encoding.ASCII.GetString(buffer, 0, bytesread)); 
      string a = compmess.ToString(); 
      string g; 
     } 
     System.Diagnostics.Debug.WriteLine(compmess.ToString()); 
     cli.Close(); 
    } 
} 
} 
+0

어떻게 '클라이언트'를 만드나요? 어떤 서버에 연결하고 있습니까? 'Read()'가 리턴하지 않는 가장 큰 이유는 서버가 어떤 데이터도 보내지 않는다는 것입니다. 그리고'catch '와'break'를 사용하는 방식은 매우 잘못된 것처럼 보입니다. 또한 스크린 샷이 아닌 텍스트로 코드를 게시 할 수 있습니까? – svick

+0

내 게시물에 있습니다. – user35443

+1

멈추지 않으면 막습니다. 뭔가를 보내십시오. –

답변

0

. 당신은 서버를 썼습니다. 여기 는 클라이언트의 예입니다 (이 테스트되고 서버와 코드와 함께 작동) :

TcpClient client = new TcpClient("localhost", 20345); 
    NetworkStream stream = client.GetStream(); 

    while (true) 
    { 
     string message = Console.ReadLine(); 
     Byte[] data = System.Text.Encoding.ASCII.GetBytes(message); 
     // Send the message to the connected TcpServer. 
     stream.Write(data, 0, data.Length); 
    } 

    stream.Close(); 
    client.Close(); 

별도의 콘솔 응용 프로그램이 클라이언트를 넣고, 다음 :

  • 서버를 시작
  • 는 새로운 비주얼 스튜디오 인스턴스에서 클라이언트를 시작하거나, 당신의 단계 O를 통해 이동합니다
  • 다음 클라이언트 콘솔 창에 exe 인에게
  • 유형 뭔가를 시작합니다 f 사용중인 StringBuilder을 업데이트하십시오.
+0

글쎄, 왜 당신의 클라이언트가 작동하지 않는 것보다? 그것이 나를 위해 일하는 것이 그것이 코드 문제가 아니라는 것을 의미한다면, 어떤 종류의 설정 일 수 있습니다. – misha

+0

클라이언트가 작동하지만 서버가 작동하지 않습니다. 하지만 내 방화벽이 포트를 차단하고있을 가능성이 있습니다. – user35443

+0

나는 그것이 가능할 수 있도록 연결을 "허용"할 것인지 묻는 메시지가 나타났습니다 ... – misha