C# 测试插座是否连接在C中#
您好,我正在编写一个简单的服务器程序,用于侦听连接。我的问题是,如何测试插座是否连接。这是我的密码C# 测试插座是否连接在C中#,c#,sockets,networking,C#,Sockets,Networking,您好,我正在编写一个简单的服务器程序,用于侦听连接。我的问题是,如何测试插座是否连接。这是我的密码 using System; using System.Net; using System.Net.Sockets; class server { static int port = 0; static String hostName = Dns.GetHostName(); static IPAddress ipAddress; static bool liste
using System;
using System.Net;
using System.Net.Sockets;
class server
{
static int port = 0;
static String hostName = Dns.GetHostName();
static IPAddress ipAddress;
static bool listening = true;
public static void Main(String[] args)
{
IPHostEntry ipEntry = Dns.GetHostByName(hostName);
//Get a list of possible ip addresses
IPAddress[] addr = ipEntry.AddressList;
//The first one in the array is the ip address of the hostname
ipAddress = addr[0];
TcpListener server = new TcpListener(ipAddress,port);
Console.Write("Listening for Connections on " + hostName + "...");
do
{
//start listening for connections
server.Start();
} while (listening);
//Accept the connection from the client, you are now connected
Socket connection = server.AcceptSocket();
Console.Write("You are now connected to the server");
connection.Close();
}
}
server.Start()
应该在循环之外。只调用一次,侦听套接字将保持打开状态,直到调用Stop
AcceptSocket
将阻塞,直到客户端连接。如果您希望能够接受多个套接字,那么请继续循环它。我认为您的bean在这里搞砸了。在操作系统级别,下面有两个截然不同的概念:侦听套接字(即TcpListener
)和连接套接字(即成功accept()
)后得到的套接字)
现在,侦听TCP套接字未连接,而是绑定到本地计算机上的端口(可能还有地址)。这就是服务器等待来自客户端的连接请求的地方。一旦这样的请求到达,操作系统就会创建一个新的套接字,这个套接字在某种意义上是连接的,因为它包含了通信所需的所有四个部分——本地IP地址和端口,以及远程地址和端口
从一些介绍性的文本开始,比如。更好——从a开始。你是什么意思?您是在询问服务器是否有任何活动连接,还是询问
连接当前是否已连接?