如何修复客户端应用程序的端口
本文关键字:应用程序 何修复 客户端 | 更新日期: 2023-09-27 18:31:54
我正在Visual Studio(c#)中开发控制台应用程序。我需要不断侦听服务器定义的IP和端口。从该IP和端口收听时,我将从epabx获取通话记录的数据。问题是我正在开发客户端套接字将通过操作系统选择的任何空闲端口进行通信。 PBX 只允许通过预配置的端口号进行通信。我没有找到任何关于如何提前为客户端配置端口的答案,以便应用程序仅从该端口进行通信。任何帮助都会很好。
许多人显示更改Web应用程序的端口,但我想为控制台应用程序配置端口。这是我的代码示例,如果它以任何方式有帮助:
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());
}
}
}
}
}
您注释的任何行都足以设置本地端点端口号。
IPEndPoint ipLocalEndPoint = new IPEndPoint(localIPAddress, clientPort);
TcpClient clientSocket = new TcpClient(ipLocalEndPoint);
clientSocket.Connect(serverIP, serverPort);