通过大量的学习和研究,我写了一个服务器端程序。但是这个程序的问题是它不接受多个客户端,我也想知道如何将输出发送回客户端而不是在服务器端显示它。有人可以帮我解决问题吗?这是我到现在为止所尝试的 -
课程计划 {
private static Regex _regex = new Regex("not|http|console|application", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
static void Main(string[] args)
{
{
TcpListener serversocket = new TcpListener(8888);
TcpClient clientsocket = default(TcpClient);
serversocket.Start();
Console.WriteLine(">> Server Started");
clientsocket = serversocket.AcceptTcpClient();
Console.WriteLine("Accept Connection From Client");
try
{
using (var reader = new StreamReader(clientsocket.GetStream()))
{
string line;
int lineNumber = 0;
while (null != (line = reader.ReadLine()))
{
lineNumber += 1;
foreach (Match match in _regex.Matches(line))
{
Console.WriteLine("Line {0} matches {1}", lineNumber, match.Value);
}
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
}
clientsocket.Close();
serversocket.Stop();
Console.WriteLine(" >> exit");
Console.ReadLine();
}
}
}
答案 0 :(得分:0)
您可以将其更改为此类内容。
static void Main(string[] args)
{
TcpListener serversocket = new TcpListener(8888);
TcpClient clientsocket = default(TcpClient);
serversocket.Start();
Console.WriteLine(">> Server Started");
while(true)
{
clientsocket = serversocket.AcceptTcpClient();
Console.WriteLine("Accept Connection From Client");
LineMatcher lm = new LineMatcher(clientsocket);
Thread thread = new Thread(new ThreadStart(lm.Run));
thread.Start();
Console.WriteLine("Client connected");
}
serversocket.Stop();
Console.WriteLine(" >> exit");
Console.ReadLine();
}
然后让这个单独的类处理线匹配
public class LineMatcher{
private static Regex _regex = new Regex("not|http|console|application", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private TcpClient _client;
public LineMatcher(TcpClient client)
{
_client = client;
}
public void Run()
{
try
{
using (var reader = new StreamReader(_client.GetStream()))
{
string line;
int lineNumber = 0;
while (null != (line = reader.ReadLine()))
{
lineNumber += 1;
foreach (Match match in _regex.Matches(line))
{
Console.WriteLine("Line {0} matches {1}", lineNumber, match.Value);
}
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
}
Console.WriteLine("Closing client");
_client.Close();
}
}
这纯粹是一个概念证明,并不是稳定的代码;)
请注意,这不会以任何方式管理子线程
由于while(true)