Socket.Send和Receive ..我如何进一步继续?

时间:2012-03-26 07:00:45

标签: c# .net sockets

我必须编写一个程序来检查文件中是否存在任何随机字符串。我这样做..但现在我被要求使用sockets.send和接收方法。我已经创建了一个连接并将代码写到这里..我该如何进一步继续?我无法弄清楚..第一个程序是我在服务器端程序的尝试。第二个是我从文件中搜索字符串的实际程序。有人可以帮助我解决如何在我的实际程序中使用套接字的代码吗?非常感谢.. :))

class Program
{
    static void Main(string[] args)
    {
        TcpListener serversocket = new TcpListener(8888);
        int requestcount = 0;
        TcpClient clientsocket = default(TcpClient);
        serversocket.Start();
        Console.WriteLine(">> Server Started");
        clientsocket = serversocket.AcceptTcpClient();
        Console.WriteLine("Accept Connection From Client");
        requestcount = 0;


        while ((true))
        {
            try
            {
                requestcount = requestcount + 1;
                NetworkStream networkstream = clientsocket.GetStream();
                byte[] bytesFrom = new byte[10025];
                networkstream.Read(bytesFrom, 0, (int)clientsocket.ReceiveBufferSize);
                string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                Console.WriteLine(" >> Data from client - " + dataFromClient);
                string serverResponse = "Server response " + Convert.ToString(requestcount);
                Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
                networkstream.Write(sendBytes, 0, sendBytes.Length);
                networkstream.Flush();
                Console.WriteLine(" >> " + serverResponse);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
        clientsocket.Close();
        serversocket.Stop();
        Console.WriteLine(" >> exit");
        Console.ReadLine();
       }
  } 

这是我想在上述程序中使用的程序。

课程计划     {

    static void Main(string[] args)
    {
        if (File.Exists("C://myfile2.txt"))
        {
            var text = File.ReadAllText("C://myfile2.txt");


            foreach (var word in new[] { "and", "so", "not", "c", "to", "by", "has", "do", "behavior", "dance", "france", "ok","thast", "please","hello","system","possible","impossible","absolutely","sachin","bradman","schumacher","http","console","application" })
            {
                var w = word;

                new Thread(() => Console.WriteLine("{0}: {1}", w, text.Contains(w) ? "Present" : "Not Present")).Start();
            }

        }
        else
            Console.WriteLine("File Does not exist");
        Console.ReadLine();
    }

}

1 个答案:

答案 0 :(得分:2)

这是一个快速而肮脏的想法,我在没有IDE的情况下写过(---我还没有测试过它--- 编辑刚用netcat测试过它,它运行正常):< / p>

  • 注意它使用正则表达式。如果单词的查找表增长得足够大,那么最好将单词存储在HashSet<string>中并将输入分成单词。然后,您可以有效地执行.IntersectWith以查看是否有任何单词匹配。

  • 请注意,不推荐使用套接字的构造函数(您应该明确指定并绑定到的IPAddress)

  • 您的原始代码不要求匹配为单独的字词(candy匹配cand)。您可能想要修复

  • 原始“grep”代码段中效率低下的部分:

    • ReadAllText(不会缩放大文件)
    • 在循环中执行多个.Contains调用的效率远远低于使用(预编译)正则表达式
    • 为什么在那里创建线程?这实际上只会增加运行时开销,并可能由于对Console.Out的不同步访问而导致问题。

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

class Program
{
    private static Regex _regex = new Regex("and|so|not|c|to|by|has|do|behavior|dance|france|ok|thast|please|hello|system|possible|impossible|absolutely|sachin|bradman|schumacher|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();
    }
}