简体   繁体   中英

Tcp Server/Client Application to communicate with other PCs

i'm trying to make an application which allows the connection between 2 PCs(i planned on making it multi threaded later but lets keep it more simple at the beginning). This could be either used for chatting or sending data to the other pc and he does something to the data and sends it back. This is my coding so far:

Server:

class Program
{
    private static StreamWriter serverStreamWriter;
    private static StreamReader serverStreamReader;

    private static bool StartServer()
    {
        //setting up Listener
        TcpListener tcpServerListener = new TcpListener(IPAddress.Any, 56765);
        tcpServerListener.Start();
        Console.WriteLine("Server Started!");
        Console.WriteLine("Waiting for Connection...");
        Socket serverSocket = tcpServerListener.AcceptSocket();
        try
        {
            if (serverSocket.Connected)
            {
                Console.WriteLine("Client connected to Server!");
                //open network stream on accepted socket
                NetworkStream serverSockStream = new NetworkStream(serverSocket);
                serverStreamWriter = new StreamWriter(serverSockStream);
                serverStreamReader = new StreamReader(serverSockStream);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.StackTrace);
            return false;
        }

        return true;
    }

    static bool once = false;

    static void Main(string[] args)
    {
        //Set Console Window Stuff
        Console.Title = "Server";
        Console.BackgroundColor = ConsoleColor.Black;
        Console.ForegroundColor = ConsoleColor.Green;
        Console.BufferWidth = 120;
        Console.Clear();

        //Start Server
        if (!StartServer())
            Console.WriteLine("Error while Starting Server!");

        //Waiting till Client sends Something
        while (true)
        {
            string data = "Append Something to Me - ";
            if (!once)//that check -.-
            {
                serverStreamWriter.WriteLine(data);
                serverStreamWriter.Flush();
                once = true;
            }
            Console.WriteLine("Client: " + serverStreamReader.ReadLine());
            if (serverStreamReader.ReadLine() != data)
            {
                serverStreamWriter.WriteLine(data);
                serverStreamWriter.Flush();
            }
        }
    }
}

Client:

class Program
{
    private static StreamReader clientStreamReader;
    private static StreamWriter clientStreamWriter;

    private static bool ConnectToServer()
    {
        try
        {
            TcpClient tcpClient = new TcpClient("127.0.0.1", 56765);
            Console.WriteLine("Connected to Server!");
            NetworkStream clientSockStream = tcpClient.GetStream();
            clientStreamReader = new StreamReader(clientSockStream);
            clientStreamWriter = new StreamWriter(clientSockStream);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.StackTrace);
            return false;
        }

        return true;
    }

    private static void SendToServer(string message)
    {
        try
        {
            clientStreamWriter.WriteLine(message);
            clientStreamWriter.Flush();
        }
        catch (Exception se)
        {
            Console.WriteLine(se.StackTrace);
        }
    }

    static void Main(string[] args)
    {
        //Set Console Window Stuff
        Console.Title = "Client";
        Console.BackgroundColor = ConsoleColor.Black;
        Console.ForegroundColor = ConsoleColor.Red;
        Console.BufferWidth = 120;
        Console.Clear();

        if (!ConnectToServer())
            Console.WriteLine("Error while Connecting to Server!");

        SendToServer("Send Me Data...");

        //Waiting till Server sends Something
        while (true)
        {
            string response = clientStreamReader.ReadLine();
            Console.WriteLine(response + "|| Appending Text...");
            response += "Appended Text!";
            Console.WriteLine("Sended " + response + " back to server!");
            SendToServer(response);
        }
    }
}

Even though this isn't really good coding, it works for me, BUT the main problem with this is it only works on my local machine. How would i make it so if i run the server app on my pc and my friend runs the client app on his pc those two connect!? Help would be really great since i wasn't able to found a detailed tutorial or such and i only created this Account to ask for help here :)

TcpClient tcpClient = new TcpClient("localhost", 3333);

Instead of "localhost", use the remote machine's address here.

Edit:

You don't seem to understand how this connection process works, so I'll try to explain it a little better.

Your server is opening up a socket on port 3333, listening for any connections. This process does not need any external IP adress.

You clients are trying to connect to the server. They need to know what server they're connecting to, so you need to supply them with an IP address. An example would be something like

TcpClient tcpClient = new TcpClient("127.0.0.1", 3333); 
//this is identical to using "localhost"

There's no way for you to get around at some point using a remote address in the connection protocol. You can't just tell the client "connect on port 3333" and expect it to know exactly where it needs to connect.

The comment explaining how to resolve a local IP address isn't useful in your case, because what you ended up doing was just telling the client to connect to itself, as you resolved the client's IP address and tried to connect to that.

However, you can have multiple clients connect to the same server. In this case you won't need multiple remote IP addresses, you just tell all the clients to connect to the same remote address and then handle that on the server. This is where the RemoteEndPoint comes into effect.

At the server level you can use the RemoteEndPoint to find the IP address of the clients connecting to it, and use this IP address to return information to those clients.

All in all, you WILL have to use some hardcoded address for your initial

TcpClient tcpClient = new TcpClient(address, 3333);

step. There's no way around this.

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