![](/img/trans.png)
[英]How do I specify a valid port when testing a client and server socket application?
[英]how to fix port for client application
我正在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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.