服务器和客户端连接C#之间的通信

时间:2016-04-01 11:46:04

标签: c# .net tcp tcpclient networkstream

我正在为我的学校项目做点什么,它要求我构建一个C#应用程序,它允许来自服务器(监听器)和客户端的通信。问题是,我已经这样做了,但它根本不起作用,它抛出了太多的错误来纠正,并且肯定编码很糟糕,我以前从来没有做过这么草率的事情。

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

很抱歉,如果我已经解释清楚了。感谢。

修改

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;
            }

        }
     */
}

1 个答案:

答案 0 :(得分:0)

根据你的解释,我无法弄清楚你想要什么,但从我的猜测来看,这取决于你想要的技术。我建议使用WCF Windows Communication Foundation。 您可以在.NET FoundationTutorial to get started

上找到一些好文章
相关问题