0
저는 클라이언트/서버를 작성하고 있습니다 (여러분 중 많은 사람들이 이미 알고있는 것처럼!). 서버가 클라이언트에 데이터를 보낼 것입니다. 그러나 클라이언트는 한 번 연결 한 후 연결이 종료되면 다시 연결하려고 시도하지 않습니다. 마찬가지로, 일단 서버가 메시지를 보내면 향후 연결 시도를 무시합니다.클라이언트/서버 모두 1 회 연결 후 포기합니다
서버 :
public Server(String p)
{
path = p;
listener = new TcpListener(IPAddress.Any, 1337);
listener.Start();
Thread t = new Thread(new ThreadStart(ListenForClients));
t.IsBackground = true;
t.Start();
}
private void ListenForClients()
{
TcpClient client = listener.AcceptTcpClient();
new Thread(new ParameterizedThreadStart(HandleClientCom)).Start(client);
}
private void HandleClientCom(object TcpClient)
{
new Dialog("Connection", "Connection established.");
TcpClient client = (TcpClient)TcpClient;
NetworkStream stream = client.GetStream();
//SslStream stream = new SslStream(client.GetStream());
//stream.AuthenticateAsServer(new X509Certificate(path + "\\ServerCert.cer"));
ASCIIEncoding encoder = new ASCIIEncoding();
String str = "This is a long piece of text to send to the client.";
byte[] bytes = encoder.GetBytes(str);
stream.Write(bytes, 0, bytes.Length);
stream.Flush();
}
클라이언트 : 코드의 엄청난 양에 대한
public TCP(BackgroundWorker b)
{
try
{
bw = b;
client = new TcpClient();
IPEndPoint server = new IPEndPoint(IPAddress.Parse(srv), 1337);
client.Connect(server); //Connect to the server
bw.ReportProgress(0); //Update the GUI with the connection status
Thread t = new Thread(new ParameterizedThreadStart(HandleComms));
t.IsBackground = true;
t.Start(client);
}
catch (Exception ex)
{
lastException = ex;
}
}
public void HandleComms(object c)
{
Boolean keepListening = true;
TcpClient client = (TcpClient)c;
NetworkStream stream = client.GetStream();
//stream = new SslStream(client.GetStream());
//stream.AuthenticateAsClient(srv);
byte[] msg = new byte[4096]; ;
int bytesRead = 0;
while (keepListening)
{
try
{
bytesRead = stream.Read(msg, 0, 4096);
}
catch (Exception ex)
{
lastException = ex;
}
if (bytesRead > 0)
{
StreamWriter writer = new StreamWriter("C:\\Users\\Chris\\Desktop\\ClientLog.txt");
ASCIIEncoding encoder = new ASCIIEncoding();
rx = encoder.GetString(msg);
writer.WriteLine(rx);
keepListening = false;
writer.Close();
}
}
}
죄송합니다. 어쨌든 제가 잘못한 곳을 지적 할 수 있습니까?
물론에 자리! – Bailz