2012-03-28 33 views
0

基本上我编写了这个程序来检查字符串。我为此使用了套接字方法。套接字接受多个客户端,但我无法打开文件

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

我该如何改进此计划?有人可以帮我解决这个问题吗?

这是我的计划:

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(); 
    } 
} 
+0

没有客户端代码。客户端代码(通常)是另一个应用程序,因为这是(网络)套接字发光的地方。 – sehe 2012-03-29 06:22:25

+0

@sehe你能帮我吗? :) – 3692 2012-03-29 06:25:37

回答

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"); 
      } 
     } 
    } 
} 
+0

非常谢谢你。 :)我真的很高兴你帮助我彻底解决问题。 :)希望至少有一次在未来,我将能够回答任何问题的..大声笑..仍然是一个新手,直到那时.. :) – 3692 2012-03-29 10:52:49