简体   繁体   中英

how to fix port for client application

I am developing console application in visual studio(c#). I need to continuously listen from server's defined IP & port. On listening to from that IP & port I will get data of call logs from epabx . Problem is I am developing client socket will communicate through any free port selected by OS. PBX only allows to communicate through pre-configured port number. I don't find any answer about how to configure port for client in advance so that application communicates from that port only. Any help will be good.

Many showed to change port for web application but i want to configure port for console application. Here is my code sample if it helps in any way:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ClientSocket
{
    public class Program
    {
        static void Main(string[] args)
        {
            TcpClient clientSocket = new TcpClient();
            clientSocket.Connect(destinationPort, destinationPort);
            //((System.Net.IPEndPoint)(clientSocket.Client.LocalEndPoint)).Port = 3389; I want to fix my port in advance something like this or any other way
            Console.WriteLine(" >> Client Started");

            while (true)
            {
                try
                {
                    NetworkStream serverStream = clientSocket.GetStream();
                    byte[] outStream = System.Text.Encoding.ASCII.GetBytes("" + "$");
                    Console.WriteLine("\nPing to Server:");
                    serverStream.Write(outStream, 0, outStream.Length);
                    serverStream.Flush();

                    byte[] inStream = new byte[10025];
                    serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
                    string returndata = System.Text.Encoding.ASCII.GetString(inStream);
                    Console.WriteLine("Reply from server:" + returndata);
                    Thread.Sleep(5000);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }
    }
}

Whatever you commented line will be enough to set local end point port number.

IPEndPoint ipLocalEndPoint = new IPEndPoint(localIPAddress, clientPort);
TcpClient clientSocket = new TcpClient(ipLocalEndPoint);
clientSocket.Connect(serverIP, serverPort);

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