2012-03-28 73 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