![](/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.