简体   繁体   中英

Communication between server and client connection C#

I'm doing something for my project for school, it requires me to build a C# application which allows both communication from the server(the listener) and the client. The problem is, I have done this, but it doesn't work at all, it throws too many errors to correct and is definitely badly coded, I've never done something this sloppy before.

I'd also want many clients to be able to access the server at the same time, so a client list of active people. I saw one example online but it was too complicated for the task that I was trying to achieve. I just want a simple text communication to both client and server and send information whenever needed to. I don't want it to be stuck in a while loop waiting for information to be sent & whatnot.

Sorry if I've badly explained it. Thanks.

edit

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

        }
     */
}

From what you explained i cannot really figure out what you want but from my guessing let's say it depends on the technology you want to go. I would recommend to use WCF Windows Communication Foundation. You can find some good articles on .NET Foundation , Tutorial to get started

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM