套接字接受多个客户端,但我无法打开该文件

时间:2012-03-28 11:08:06

标签: c# .net sockets

基本上我已经编写了这个程序来检查字符串。我已经使用套接字方法了。

问题是,我无法弄清楚如何以及在何处准确地打开此程序中​​的文件并搜索字符串。我希望客户端能够键入/搜索他们想要的任何字符串,而不是在程序中提供搜索字符串。当我运行程序时,我需要客户端屏幕上的输出。

如何改进此计划?有人可以帮我解决一下代码吗?

这是我的计划:

class Program
{
    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");
        }
        Console.WriteLine(" >> exit");
        Console.ReadLine();
        clientsocket.Close();
        serversocket.Stop();
    }
}
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();
    }
} 

1 个答案:

答案 0 :(得分:1)

这是一个适合我的简单演示客户端:

using System;
using System.IO;
using System.Net.Sockets;
using System.Text;

namespace AClient
{
    class Client
    {
        static void Main()
        {
            using (var client = new TcpClient("localhost", 8888))
            {
                Console.WriteLine(">> Client Started");

                using (var r = new StreamReader(@"E:\input.txt", Encoding.UTF8))
                using (var w = new StreamWriter(client.GetStream(), Encoding.UTF8))
                {
                    string line;
                    while (null != (line = r.ReadLine()))
                    {
                        w.WriteLine(line);
                        w.Flush(); // probably not necessary, but I'm too lazy to find the docs
                    }
                }

                Console.WriteLine(">> Goodbye");
            }
        }
    }
}