我正在尝试学习C#中的套接字编程 通过使用Google,我发现了很多很好的教程和示例。 但是这是我自己的代码:
发件人应用程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net; // socket library
using System.Net.Sockets; // socket library
namespace Sender
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter remote IP : ");
IPAddress ipAddress = IPAddress.Parse(Console.ReadLine());
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sender.Connect(ipAddress, 4444);
Console.Write("Enter text to send : ");
byte[] message = Encoding.ASCII.GetBytes(Console.ReadLine().ToString());
sender.Send(message);
sender.Shutdown(SocketShutdown.Both);
sender.Close();
Console.ReadKey();
} // main
} // main
} // main
接收器应用程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net; // socket library
using System.Net.Sockets; // socket library
namespace Listener
{
class Program
{
static void Main(string[] args)
{
IPAddress ipAddress = Dns.GetHostAddresses(Dns.GetHostName()).Where(address => address.AddressFamily == AddressFamily.InterNetwork).First();
Console.WriteLine("Listening on " + ipAddress.ToString() + " : 4444");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 4444);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(10);
Socket handler = listener.Accept();
byte[] bytes = new Byte[1024];
int bytesRec = handler.Receive(bytes);
Console.WriteLine(Encoding.ASCII.GetString(bytes, 0, bytesRec));
handler.Shutdown(SocketShutdown.Both);
handler.Close();
listener.Close();
Console.ReadKey();
} // main
} // main
} // main
代码工作正常,但是我想知道为什么在服务器端需要两个套接字?第一个是侦听器,第二个是处理程序。可以省略其中之一,使代码变得更简单吗?
通过我的代码基于这些代码的方式:
我也在使用Microsoft Visual C#2008 Express Edition
答案 0 :(得分:1)
侦听器套接字正在侦听传入的连接。如果没有处理程序套接字,那么在与客户端的通信结束之前,没有人可以监听并行的传入连接。
这就是Accept
返回另一个用于通信的套接字,而监听套接字继续等待传入连接的原因。
您可以将其视为一种弱类型的对象:套接字负责侦听和通信角色,尽管为这两个不同的任务使用不同的类型可能更好。但是这种行为反映了traditional socket的行为,因此它保持原样,以便对具有网络编程背景的人们熟悉。
更高级的API(TcpListener
和TcpClient
)在监听和通信角色之间有明显的区别。