服务器连接错误

时间:2011-11-13 12:51:01

标签: c# sockets communication tcpclient networkstream

我现在正在尝试使用服务器。我有这个代码: 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();
    }
}
}

1 个答案:

答案 0 :(得分: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();

将此客户端放在单独的控制台应用程序中,然后:

  • 启动服务器
  • 然后在新的Visual Studio实例中启动客户端,或启动exe
  • 在客户端控制台窗口中键入内容
  • 接下来,您将完成更新正在使用的StringBuilder的步骤。