c# - 无法连接到本地主机。是客户端问题还是本地主机问题?
问题描述
我正在尝试创建一个线程,以使侦听器在 127.0.0.1 处保持活动状态。我正在使用以下代码来创建侦听器:
IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); //Localhost Ip Address
TcpListener connectionListner = new TcpListener(ipAddress, 2003);
connectedSocket = connectionListner.AcceptSocket();
connectionListner.Start();
我在客户端面临问题。当我尝试将客户端连接到上面创建的 localhost(单独的程序)时,出现错误。
客户代码:
class Client
{
static void Main(string[] args)
{
Console.WriteLine("client has started." + Environment.NewLine);
connectToLocalHost();
}
static void connectToLocalHost()
{
string ipaddress = "127.0.0.1";
int port = 2003;
try
{
TcpClient client = new TcpClient(ipaddress, port);
NetworkStream stream = client.GetStream();
Byte[] data = new Byte[256]; // Buffer to store the response bytes.
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
// Close everything.
stream.Close();
client.Close();
}
catch (SocketException SE)
{
Console.WriteLine("Socket Error..... " + SE.StackTrace);
}
}
}
错误:
Message = "无法建立连接,因为目标机器主动拒绝 127.0.0.1:2003"
解决方案
推荐阅读
- javafx - 如何使用 javafx 制作视频播放器?
- express - 如何在作为快速中间件实现的 Jayson RPC 服务器中设置响应标头
- continuous-integration - 如何在 CI 中设置应用程序凭据详细信息?
- java - 默认 Spring Boot Thymeleaf 配置位置
- postgresql - postgresql 复制的大小太大
- java - 从扫描仪获取输入并用逗号分割 - 将其存储在数组中
- amazon-web-services - AWS Lambda VScode 启动.json
- android - 如何在 RecyclerView 适配器中获取第二个模型的位置
- javascript - 当在 Javascript 上调用 Mathjax 并且我想输出变量的值时,如何通过 Mathjax 渲染公式?
- c++ - 虚幻引擎 4.25、stdlib C++ 17/20 和 Visual Studio Code 之间的状态和/或集成?