日期:2014-05-18  浏览次数:20857 次

如何创建一个可以接收内外网信号的服务?
我想用.net创建一个服务程序,可以接收局域网和广域网上的信号,并根据信号的内容做出相应动作,敢问各位大虾这样的程序如何实现,有否相应例子可供参考。我的邮箱comwin@126.com,谢谢!

------解决方案--------------------
sf
------解决方案--------------------
?不太懂,帮你顶一下吧。
------解决方案--------------------
服务必须放在有外网的IP的服务器上。
双网卡就解决了。

------解决方案--------------------
用TCP或socket都可以,不过我只做过局域网的。
------解决方案--------------------
那用.net remoting,只不过这个东西不可跨平台。所以为了通用性还是选择webservice
------解决方案--------------------
你这是要做什么?说的太含糊
------解决方案--------------------
这里有一个服务端的程序,监听的端口是4554,在路由器上把外网的这个端口映射过来就行了。
C# code

using System;
using System.Net.Sockets;
using System.Net ;
using System.Threading ;

public class DateServer 
{
    private TcpListener myListener ;
    private int port = 4554 ;
    
    public DateServer()
    {
        try
        {
            //start listing on the given port
            myListener = new TcpListener(port) ;
            myListener.Start();
            Console.WriteLine("Server Ready - Listining for new Connections ...") ;
            //start the thread which calls the methor SatrtListen
            Thread th = new Thread(new ThreadStart(StartListen));
            th.Start() ;                
        }
        catch(Exception e)
        {
            Console.WriteLine("An Exception Occured while Listing :"+e.ToString());
        }
        
    }

    public static void Main(String[] argv)
    {
        DateServer dts = new DateServer();
    }
    
    public void StartListen()
    {
        while(true)
        {
            //Accept a new connection
            Socket mySocket = myListener.AcceptSocket() ;
            if(mySocket.Connected)
            {
                Console.WriteLine("Client Connected!!") ;
                //make a byte array and receive data from the client 
                Byte[] receive = new Byte[64] ;
                int i=mySocket.Receive(receive,receive.Length,0) ;
                char[] unwanted = {' ',' ',' '};
                string rece = System.Text.Encoding.ASCII.GetString(receive);
                Console.WriteLine(rece.TrimEnd(unwanted)) ;
                
                //get the current date/time and convert it to string
                DateTime now = DateTime.Now;
                String strDateLine ="Server: The Date/Time Now is: "+ now.ToShortDateString() + " " + now.ToShortTimeString();
            
                // Convert to byte array and send
                Byte[] byteDateLine = System.Text.Encoding.ASCII.GetBytes(strDateLine.ToCharArray());
                mySocket.Send(byteDateLine,byteDateLine.Length,0);                
            }
        }
    }
}