【问题标题】:Communication between server and client connection C#服务器和客户端连接C#之间的通信
【发布时间】:2016-07-21 05:07:11
【问题描述】:

我正在为我的学校项目做一些事情,它需要我构建一个 C# 应用程序,该应用程序允许来自服务器(侦听器)和客户端的通信。问题是,我已经这样做了,但它根本不起作用,它会引发太多错误而无法纠正,而且编码肯定很糟糕,我以前从未做过如此草率的事情。

我还希望多个客户端能够同时访问服务器,因此需要一个活跃人员的客户端列表。我在网上看到了一个例子,但它对于我试图完成的任务来说太复杂了。我只想与客户端和服务器进行简单的文本通信,并在需要时发送信息。我不希望它陷入等待发送信息的循环中。

对不起,如果我解释得不好。谢谢。

编辑

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace CentralHubGUI
{
    class chCon
    {  



    static TcpClient clientCon;
    static NetworkStream stream;
    public static bool currentlyConnected;

    static string buffer;

    string ip = "";
    int port = 0;

    Thread thread1 = new Thread(receiveData_Stage1);
    //Thread thread2 = new Thread();
    //Thread thread3 = new Thread(); 

    public chCon(string ipAddress, int portNumber)
    {
        ip = ipAddress;
        port = portNumber;

        connectToConsole();
    }

    public void connectToConsole()//mitigates the connection
    {
        if (ip.Trim() == "")
            ip = "127.0.0.1";

        if (port == 0)
            port = 2647;

        try
        {
            clientCon = new TcpClient(ip, port);
            stream = clientCon.GetStream();

            sendData("#101" + (char)13); //first bit of data is sent on accepted client

            Thread retrieveData = new Thread(receiveData_Stage1);
            retrieveData.Start();
            currentlyConnected = true;

            thread1.Start(); //starting to read the server for information 
        }

        catch(Exception e) // if the connection being naughty ;)
        {
            currentlyConnected = false;
            MessageBox.Show("Exception caught:\n" + e);
        }

    }

    public void disconnectFromConsole()
    {
        try
        {
            if (clientCon.Connected || clientCon.Connected == null)
            {
                thread1.Abort();

                byte[] msg = System.Text.Encoding.ASCII.GetBytes("#103");
                stream.Write(msg, 0, msg.Length);
                stream.Close();
                clientCon.Close();

                currentlyConnected = false;
            }
            else
            {
                MessageBox.Show("Cannot disconnect from a connection that has not started.");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error thrown during disconnection - UNKNOWN");
        }
    }

    internal void sendData(string data)//sends data to the server
    {
        Byte[] dataConv = System.Text.Encoding.ASCII.GetBytes(data);

        stream.Write(dataConv, 0, dataConv.Length);

    }

    public static void receiveData_Stage1() //builds a buffer through a loop
    {
        while (true)
        {
            Byte[] response = new Byte[256];
            string responseData = String.Empty;

            // Read the first batch of the TcpServer response bytes.
            Int32 bytes = stream.Read(response, 0, response.Length);
            responseData = System.Text.Encoding.ASCII.GetString(response);

            if(responseData.Trim() != "")
                buffer = buffer + responseData;
        }
    }

    public static string receiveData_Stage2() //requests the buffer through a return value string
    {
        string bufferTemp;
        bufferTemp = buffer;

        buffer = string.Empty;

        return bufferTemp;
    }

    public void closeConnection()
    {
        stream.Close();
        clientCon.Close();
        thread1.Abort();
    }

    }
    /*
    while (true)
        {
            if (Program.currentlyConnected == true)
            {
                Thread.Sleep(100);
                buffer = Program.receiveData_Stage2();
                if (buffer != "")
                    richTxtBoxConsole.AppendText(buffer + "\n");
            }
            else
            {
                guiConsoleWriteLine("Connection is not active.");
                break;
            }

        }
     */
}

【问题讨论】:

  • 发布您尝试过的内容。否则这个问题太笼统了。
  • 这个问题需要认真研究。请准确说明您尝试过的内容以及遇到的无法解决的错误/问题。
  • A) 为什么要使用两个线程来读取数据?这可能会导致严重的问题。要么摆脱Thread1retrieveDataB) 检查clientCon.Connected == null 是没有用的,因为Boolean 的值不能为空。

标签: c# .net tcp tcpclient networkstream


【解决方案1】:

根据您的解释,我无法真正弄清楚您想要什么,但从我的猜测来看,这取决于您想要采用的技术。我会推荐使用 WCF Windows Communication Foundation。 你可以在.NET FoundationTutorial to get started找到一些好文章

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-26
    • 1970-01-01
    • 2016-02-16
    • 1970-01-01
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多