Lukas

Lukas

  • 2.1k
  • 2
  • 1.6k

TcpListener: bypass port

Aug 21 2014 3:55 PM
Hey,

together with a friend I programmed a small Client/Listener. It is working fine on local network, but if I put one of this on a server (added my ip-address in the sourcecode) I can only message the server, but server messages don't reach me. Maybe it's because I have not forwarded any ports for my program at home (I cant open ports here). Games and other programs are working fine, so there must be a solution without opening ports on my router.

I would be thankful for any solution!



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


namespace Senden
{
    class Program
    {
        static void Main(string[] args)
        {
            int port = 1337;
            string input;


            Thread ServerThread = new Thread(new ThreadStart(thread));
            ServerThread.Start();


            while (true)
            {
                input = Console.ReadLine();
                TcpClient client = new TcpClient("MYIPISHERE", port);
                byte[] message = System.Text.Encoding.ASCII.GetBytes(input);
                NetworkStream stream = client.GetStream();
                stream.Write(message, 0, message.Length);
                stream.Close();
                client.Close();
            }


        }


        static void thread()
        {
            int port = 1337;
            TcpListener server = new TcpListener(IPAddress.Any, port);
            server.Start();


            byte[] bytes = new Byte[256];
            while (true)
            {
                string message = "";
                TcpClient client = server.AcceptTcpClient();
                NetworkStream stream = client.GetStream();
                int i;
                while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    message = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                }
                Console.WriteLine(message);
            }
        }


        }
    }