ASP.NET Core集成Socket后HTTP控制器失效问题求助
Let’s break down the issues and fix your problem step by step:
First, Check for Port Conflicts
Your suspicion about ports is a good starting point. If your ASP.NET Core web app and Socket service are trying to use the same port, whichever starts first will hog the port, causing the other to fail.
- Find your ASP.NET Core port: Open the
launchSettings.jsonfile in your project. Look for theapplicationUrlproperty (e.g.,"applicationUrl": "http://localhost:5000;https://localhost:5001"). - Verify no overlap: Make sure the port used by your Socket (
1302) doesn’t match any of the ports listed here. If they do, either change the Socket port (e.g., to1303) or update the ASP.NET Core port inlaunchSettings.json.
Fix Resource Leaks in Your Socket Code
Your current Socket code doesn’t properly clean up resources like TcpClient, NetworkStream, StreamReader, and StreamWriter. Over time, this causes resource leaks that can destabilize your entire app, including the HTTP controllers. Here’s the cleaned-up version with proper resource management:
public static void ServerSocket() { Console.WriteLine("Socket server starting..."); // Use 'using' to auto-dispose the TcpListener when done using TcpListener listener = new TcpListener(System.Net.IPAddress.Any, 1302); listener.Start(); try { while (true) { Console.WriteLine("Waiting for a connection..."); // Auto-dispose the client connection with 'using' using TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("Client Accepted"); // Auto-dispose stream and readers/writers using NetworkStream stream = client.GetStream(); using StreamReader sr = new StreamReader(stream); using StreamWriter sw = new StreamWriter(stream) { AutoFlush = true }; // Enable auto-flush to avoid manual calls try { byte[] buffer = new byte[1024]; // The Read() method returns the actual number of bytes received—no need to loop through the buffer int recv = stream.Read(buffer, 0, buffer.Length); if (recv > 0) { string request = Encoding.UTF8.GetString(buffer, 0, recv); Console.WriteLine($"Received request: {request}"); sw.WriteLine("Hello darkness my old friend"); } } catch (Exception e) { Console.WriteLine($"Error handling client: {e.Message}"); // Add a try-catch here to avoid crashes if sending the error fails try { sw.WriteLine($"Error: {e.ToString()}"); } catch (Exception writeEx) { Console.WriteLine($"Failed to send error message: {writeEx.Message}"); } } } } catch (Exception ex) { Console.WriteLine($"Socket server error: {ex.Message}"); } finally { listener.Stop(); Console.WriteLine("Socket server stopped"); } }
Use ASP.NET Core Hosted Service for Background Tasks
Running your Socket in a raw thread works, but it’s not integrated with the ASP.NET Core app lifecycle. If your app shuts down unexpectedly, the Socket thread might not clean up properly. A better approach is to use a Hosted Service, which is the official way to run background tasks in ASP.NET Core:
Step 1: Create a Socket Hosted Service
public class SocketHostedService : IHostedService, IDisposable { private Thread _socketThread; private CancellationTokenSource _cts; public Task StartAsync(CancellationToken cancellationToken) { _cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); _socketThread = new Thread(() => RunSocketServer(_cts.Token)); _socketThread.Start(); return Task.CompletedTask; } private void RunSocketServer(CancellationToken token) { Console.WriteLine("Socket server starting..."); using TcpListener listener = new TcpListener(System.Net.IPAddress.Any, 1302); listener.Start(); try { while (!token.IsCancellationRequested) { // Check for pending connections to avoid blocking indefinitely if (listener.Pending()) { using TcpClient client = listener.AcceptTcpClient(); Console.WriteLine("Client Accepted"); using NetworkStream stream = client.GetStream(); using StreamReader sr = new StreamReader(stream); using StreamWriter sw = new StreamWriter(stream) { AutoFlush = true }; try { byte[] buffer = new byte[1024]; int recv = stream.Read(buffer, 0, buffer.Length); if (recv > 0) { string request = Encoding.UTF8.GetString(buffer, 0, recv); Console.WriteLine($"Received request: {request}"); sw.WriteLine("Hello darkness my old friend"); } } catch (Exception e) { Console.WriteLine($"Error handling client: {e.Message}"); try { sw.WriteLine($"Error: {e.ToString()}"); } catch (Exception writeEx) { Console.WriteLine($"Failed to send error message: {writeEx.Message}"); } } } else { // Short sleep to avoid CPU overload from empty loops Thread.Sleep(100); } } } catch (Exception ex) { Console.WriteLine($"Socket server error: {ex.Message}"); } finally { listener.Stop(); Console.WriteLine("Socket server stopped"); } } public Task StopAsync(CancellationToken cancellationToken) { _cts.Cancel(); _socketThread.Join(); return Task.CompletedTask; } public void Dispose() { _cts?.Dispose(); } }
Step 2: Register the Hosted Service
Add this to your Startup.ConfigureServices method:
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); // Register the Socket background service services.AddHostedService<SocketHostedService>(); }
Step 3: Remove the Old Thread Startup
You can now delete the thread-starting code from Startup.Configure—the Hosted Service will handle starting the Socket automatically when your app launches.
Final Checks
After making these changes:
- Restart your ASP.NET Core app.
- Test your HTTP controllers to confirm they’re responding again.
- Verify the Socket service still works with your Unity game.
内容的提问来源于stack exchange,提问作者Olotolo

