我刚刚创建了一个C#套接字服务器并且它运行良好,但如果我想让它能够监听输入程序崩溃。我的问题是:如何在客户端命令后继续监听。
这是我的代码:
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace mc_server
{
class Program
{
private static TcpListener serverSocket;
private static TcpClient clientSocket;
private static StreamReader reader;
private static StreamWriter writer;
private static int PORT = 5000;
static void Main(string[] args)
{
Console.WriteLine(DateTime.Now.ToString() + " >> Server starting...");
StartServer();
Console.ReadKey(true);
serverSocket.Stop();
}
private static void StartServer()
{
try
{
serverSocket = new TcpListener(IPAddress.Any, PORT);
serverSocket.Start();
Console.WriteLine(DateTime.Now.ToString() + " >> Server started");
while (true)
{
clientSocket = serverSocket.AcceptTcpClient();
reader = new StreamReader(clientSocket.GetStream());
writer = new StreamWriter(clientSocket.GetStream());
StartListening();
}
}
catch (Exception e)
{
if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
Console.WriteLine(DateTime.Now.ToString() + " [ERR]: Internet connection unavailable! (" + e.ToString() + ")");
else
Console.WriteLine(DateTime.Now.ToString() + " [ERR]: Server can't be started! (" + e.ToString() + ")");
}
}
private static void StartListening()
{
try
{
string line;
//while (true)
//{
line = reader.ReadLine();
if (line.Contains("connected"))
{
Console.WriteLine(DateTime.Now.ToString() + " >> Remote connected");
}
else if (line.Contains("get_dir"))
{
Console.WriteLine("in_get_dir");
foreach (string directory in Directory.GetDirectories(path))
{
DirectoryInfo dir_name = new DirectoryInfo(directory);
string dirName = dir_name.Name;
writer.WriteLine(line);
}
}
//}
}
catch (Exception e)
{
Console.WriteLine(DateTime.Now.ToString() + " [ERR]: " + e.ToString() + ")");
}
}
}
}
非常感谢你的帮助! 此致,斯坦利。
答案 0 :(得分:1)
我刚刚创建了一个C#套接字服务器并且它运行良好,但如果我想让它能够监听输入程序崩溃。
我不确定你的意思,但我认为你在接收/阅读回复时遇到了问题。
iron-ajax
您已经创建了一个名为'serverSocket'的TcpListener。现在让我们创建一个套接字,帮助我们在服务器和客户端之间发送和接收数据。创建Streamwriter和Streamreader太长而且复杂。你必须处理冲洗,处理和关闭它们。
这是我使用Socket进行沟通的简化指南:
1.。)创建套接字:
on-response
2.。)发送数据:
serverSocket = new TcpListener(IPAddress.Any, PORT);
serverSocket.Start();
3。)接收/读取数据:
Socket socket = serverSocket.AcceptSocket(); // This is a
//synchronous function. It will not execute the next line until a client
//connects to the server
答案 1 :(得分:0)
您可以使用async / await关键字在套接字上异步读取和写入数据。 这样,您的输入逻辑将保持独立。如果使用异步/等待,则不必手动管理线程。
您可以检查以下课程,以了解有关异步套接字编程的更多信息: https://www.udemy.com/tcpip-socket-programming-for-coders-using-csharp-net/couponCode=HALF