C#服务端Socket示例代码无法运行求助
C#服务端Socket示例代码无法运行求助
Hey, I’ve run into similar headaches with that Microsoft socket example before—let’s walk through what might be going wrong and fix it step by step.
First, let’s break down the common issues in the original code that could be causing your telnet connection to fail:
- If your
Mainmethod isn’t marked as async, usingawaitwill either throw a compile error or cause the program to exit prematurely before the socket even starts listening. - There’s no error handling, so you might be missing critical info like port conflicts or permission issues.
- Console apps without a wait mechanism will close immediately, leaving no time for clients to connect.
Here’s a fixed version of your code that addresses these problems, plus adds helpful status messages:
using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace SocketServerExample { class Program { // Async Main is supported in C# 7.1+ static async Task Main(string[] args) { try { IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 12000); using Socket listener = new( ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); listener.Bind(ipEndPoint); Console.WriteLine($"Server started, listening on port {ipEndPoint.Port}..."); listener.Listen(100); // Wait for a client to connect var handler = await listener.AcceptAsync(); Console.WriteLine("Client connected!"); while (true) { var buffer = new byte[1_024]; var received = await handler.ReceiveAsync(buffer, SocketFlags.None); // Handle client disconnect if (received == 0) { Console.WriteLine("Client disconnected."); break; } var response = Encoding.UTF8.GetString(buffer, 0, received); var eom = "<|EOM|>"; if (response.IndexOf(eom) > -1) { var cleanMessage = response.Replace(eom, ""); Console.WriteLine($"Socket server received message: \"{cleanMessage}\""); var ackMessage = "<|ACK|>"; var echoBytes = Encoding.UTF8.GetBytes(ackMessage); await handler.SendAsync(echoBytes, SocketFlags.None); Console.WriteLine($"Socket server sent acknowledgment: \"{ackMessage}\""); break; } } // Properly shut down the client connection handler.Shutdown(SocketShutdown.Both); } catch (Exception ex) { Console.WriteLine($"Error occurred: {ex.Message}"); } // Keep console open to view output Console.WriteLine("Press any key to exit..."); Console.ReadKey(); } } }
Key fixes and improvements:
- Async Main Method: Marks
Mainasasync static Taskso we can safely useawaitwithout the program exiting early. - Error Handling: The
try-catchblock will show you exactly what’s wrong (like a port being used by another app). - Status Messages: You’ll see when the server starts, when a client connects, and any errors that pop up.
- Disconnect Handling: Checks if
received == 0to detect when a client closes the connection gracefully. - Clean Connection Shutdown: Uses
handler.Shutdownto properly close the socket when done.
How to test this:
- Run the updated program—you’ll see "Server started, listening on port 12000..." in the console.
- Open Command Prompt and type
telnet localhost 12000—you should connect successfully. - Type
Hello<|EOM|>and press enter. The server will log your message, send back<|ACK|>, and exit the loop.
Additional troubleshooting tips:
- Check Port Usage: Run
netstat -ano | findstr :12000in Command Prompt to see if another app is using port 12000. - Firewall Settings: Temporarily disable Windows Firewall (or add an exception for your app) to rule out firewall blocks.
- .NET Version: If you’re using .NET Framework instead of .NET Core/.NET 5+, make sure your project supports async Main (you might need to adjust the syntax slightly).
备注:内容来源于stack exchange,提问作者zobbo




