不是很熟,帮你up。
另外,看看这个贴子对你有没有帮助
http://www.c-sharpcorner.com/2/window_service.asp

解决方案 »

  1.   

    以前老在asp.net版里混。象什么思归呀什么的Boss级人物,在这里我也不认识。我的问题问的也不很多。刚刚4个绿星星,就给了200分。我已经尽力了。这里的众位Boss帮帮小弟拉。
      

  2.   

    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.ServiceProcess;
    using System.Threading;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;namespace SocketS_S1
    {

    public class Service1 : System.ServiceProcess.ServiceBase
    {
    /// <summary> 
    /// 必需的设计器变量。
    /// </summary>
    private System.ComponentModel.Container components = null;
    private System.Timers.Timer timer1;
    public Thread t;
    private bool flag;
    public Service1()
    {
    // 该调用是 Windows.Forms 组件设计器所必需的。
    InitializeComponent(); // TODO: 在 InitComponent 调用后添加任何初始化
    } // 进程的主入口点
    static void Main()
    {
    System.ServiceProcess.ServiceBase[] ServicesToRun;

    // 同一进程中可以运行多个用户服务。若要将
    //另一个服务添加到此进程,请更改下行
    // 以创建另一个服务对象。例如,
    //
    //   ServicesToRun = New System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()};
    //
    ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service1() }; System.ServiceProcess.ServiceBase.Run(ServicesToRun);
    } /// <summary> 
    /// 设计器支持所需的方法 - 不要使用代码编辑器 
    /// 修改此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {
    this.timer1 = new System.Timers.Timer();
    ((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
    // 
    // timer1
    // 
    this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
    // 
    // Service1
    // 
    this.CanPauseAndContinue = true;
    this.ServiceName = "TestService";
    ((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit(); } /// <summary>
    /// 清理所有正在使用的资源。
    /// </summary>
    protected override void Dispose( bool disposing )
    {
    if( disposing )
    {
    if (components != null) 
    {
    components.Dispose();
    }
    }
    base.Dispose( disposing );
    } /// <summary>
    /// 设置具体的操作,以便服务可以执行它的工作。
    /// </summary>
    protected override void OnStart(string[] args)
    {
    // TODO: 在此处添加代码以启动服务。
    StartServer();
    timer1.Enabled=true;
    }
     
    /// <summary>
    /// 停止此服务。
    /// </summary>
    protected override void OnStop()
    {

    // TODO: 在此处添加代码以执行停止服务所需的关闭操作。
    timer1.Enabled=false;
    } private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
    flag=true;
    } private void StartServer()
    {
    IPAddress ServerIP=IPAddress.Parse("10.138.203.4");
    IPAddress ClientIP=IPAddress.Parse("10.138.204.7"); IPEndPoint ServerEP= new IPEndPoint(ServerIP,2001);
    IPEndPoint ClientEP= new IPEndPoint(ClientIP,2002); Socket ServerSocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
    ServerSocket.Bind(ServerEP);
    ServerSocket.Listen(10);

    while (true)
    {
    try
    {
    if (flag==true)
    {
    Socket ClientSocket=ServerSocket.Accept();
    byte[] bytes;
    bytes=Encoding.ASCII.GetBytes(System.DateTime.Now.ToString("hh:mm:ss:fff"));
    ClientSocket.Send(bytes,0,bytes.Length,SocketFlags.None);
    ClientSocket.Shutdown(SocketShutdown.Both);
    ClientSocket.Close();
    }
    }
    catch (Exception ex)
    {
    System.Diagnostics.Debug.WriteLine(ex.ToString());
    }
    finally
    {
    flag=false;
    }
    }
    }
    }
    }
      

  3.   

    我觉得webservice就和写类差不多阿,而且vs.net很好调用类或者webservcie的麻,不清楚你在说什么
      

  4.   

    to: melonlee(西瓜)
    不清楚你在说什么???看看题目啊!哪里有webservice这几个字
      

  5.   

    先谢谢 wangsaokui(无间道II(前传)) 兄了。再问一声,你是不是加了一个时间空件。那个控件时间设成多久触发呢。还有里面Socket 如何引用?哎~可能问题比较简单拉。不过麻烦您还是多看看。讲点简单的知识让我了解了解。我也是第一次写这个东东拉
      

  6.   

    进程没有怎么用吧?一般都是采用多线程来达到一定的目的。tencent的qq服务器会否是一个windows service呢?
      

  7.   

    不谢!时间控件你自己设定,当然也可以通过多线程的timer。
    IPAddress ServerIP=IPAddress.Parse("10.138.203.4");
    IPAddress ClientIP=IPAddress.Parse("10.138.204.7");IPEndPoint ServerEP= new IPEndPoint(ServerIP,2001);
    IPEndPoint ClientEP= new IPEndPoint(ClientIP,2002);
    设定服务器和客户端的IP地址和端口Socket ServerSocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
    ServerSocket.Bind(ServerEP);
    ServerSocket.Listen(10);
    建立一个协议为TCP,类型为流媒体的套接字
    服务器端进行监听Socket ClientSocket=ServerSocket.Accept();
    接收一个客户端的套接字bytes=Encoding.ASCII.GetBytes(System.DateTime.Now.ToString("hh:mm:ss:fff"));
    ClientSocket.Send(bytes,0,bytes.Length,SocketFlags.None);
    先将时间转变为bytes,然后向客户端发送这个bytesClientSocket.Shutdown(SocketShutdown.Both);
    ClientSocket.Close();
    关闭这个客户端的套接字
      

  8.   

    Debuging your windows service code 1.      新建一个WinForm App 或者 Console App,随便,能执行就成。2.      在这个Project 里加上和Windows Service 相同的Reference,比如System.ServiceProcess什么的。3.      然后,在这个Project 上选择 “Add Exist Item”4.      在Add Exist Item的文件选择对话框里,选定一个Windows Service Project中的cs 文件—别急着Open5.      点Open 按钮旁边的乡下箭头,在列表中选择 “Link File”6.      重复3-5,加入调试需要的所有文件7.      现在,你可以在 Console 的 Main方法 或者 Win Form的Button-Click 事件里,慢慢地弄你Windows Service里的代码了。
      

  9.   

    那个,那个。我都有点不好意思了。不过还是要问下。能不能把客户段调用这个服务的代码也放给我。我都不知道怎么调用。而且象这种在服务器端接受响应的东东,为什么还是要写在时间控件里?那main函数有什么用嘛?而且既然建立监听,还要time控件有什么用嘛?哎~不理解。帮忙了拉。我也知道麻烦你了。一会另开个200分的帖子给你。
    :)
      

  10.   

    不麻烦,我都忘了放在哪台机器上了(我有三台机器)客户端代码,屏蔽的是为了做试验
    这段代码服务器端不用timer(之所以加上是因为如果计时器从客户端启动,客户端每次连接到服务器的时间是不同的,所以得到的服务器的时间间隔会有几个毫秒的差距,为了得到统一的时间间隔,需要服务器端做计时器)   Private Sub receive()
            'Dim currentProcess As Process = Process.GetCurrentProcess()
            'currentProcess.PriorityClass = ProcessPriorityClass.RealTime
            '创建客户端的Socket
            Dim cClient As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            '指定本地回路的IP地址
            Dim MyServerIP, MyClientIP As IPAddress
            MyServerIP = IPAddress.Parse("10.138.203.4")
            MyClientIP = IPAddress.Parse("10.138.204.7")
            '设置服务器端的端口号
            Dim ServerEP As New IPEndPoint(MyServerIP, 2001)
            '设置客户端的端口号
            Dim ClientEP As New IPEndPoint(MyClientIP, 2002)
            '将Socket与端口绑定
            'cClient.Bind(ClientEP)
            Do While (True)
                Try
                    cClient.Connect(ServerEP)
                    Dim str As String ' = TxtInput.Text
                    'Dim bytes() As Byte = System.Text.Encoding.ASCII.GetBytes(str)
                    '向服务器发出请求
                    'cClient.SendTo(bytes, ServerEP)
                    Dim bytes2(500) As Byte
                    '接收服务器的响应结果
                    cClient.Receive(bytes2)
                    str = System.Text.Encoding.ASCII.GetString(bytes2)
                    'MessageBox.Show(str)
                    '将结果显示在文本框中
                    If str <> "" And IsNothing(str) = False Then
                        ListBox1.Items.Add(str)
                    End If
                Catch er As SocketException
                    MsgBox(er.ToString)
                End Try
            Loop
            '关闭Socket
            'cClient.Shutdown(SocketShutdown.Both)
            'cClient.Close()
            'Thread.Sleep(100)
        End SubPrivate Sub BSuspend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BSuspend.Click
            t.Suspend()
        End Sub    Private Sub BResume_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BResume.Click
            t.Resume()
        End Sub    Private Sub BStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BStop.Click
            t.Abort()
        End Sub    Private Sub Start_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Start.Click
            'If Timer1.Enabled = True Then
            '    Timer1.Enabled = False
            'Else
            '    Timer1.Enabled = True
            'End If
            't.Start()
            receive()
        End Sub
      

  11.   

    WinSDemo.csusing System;using System.Collections;using System.ComponentModel;using System.Data;using System.Diagnostics;using System.ServiceProcess;using System.IO;using System.Threading;namespace WinSDemo{ public class WinSDemo : System.ServiceProcess.ServiceBase { /// <summary>  /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private bool blnStopThread; private Thread thdMain; public WinSDemo() { // This call is required by the Windows.Forms Component Designer. InitializeComponent(); // TODO: Add any initialization after the InitComponent call } // The main entry point for the process static void Main() { System.ServiceProcess.ServiceBase[] ServicesToRun; // More than one user Service may run within the same process. To add // another service to this process, change the following line to // create a second service object. For example, // //   ServicesToRun = New System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()}; // ServicesToRun = new System.ServiceProcess.ServiceBase[] { new WinSDemo() }; System.ServiceProcess.ServiceBase.Run(ServicesToRun); } /// <summary>  /// Required method for Designer support - do not modify  /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { //  // WinSDemo //  this.CanPauseAndContinue = true; this.ServiceName = "MyTest"; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null)  { components.Dispose(); } } base.Dispose( disposing ); } /// <summary> /// Set things in motion so your service can do its work. /// </summary> protected override void OnStart(string[] args) { // TODO: Add code here to start your service. thdMain=new Thread(new ThreadStart(WriteLog)); thdMain.Start(); }  /// <summary> /// Stop this service. /// </summary> protected override void OnStop() { // TODO: Add code here to perform any tear-down necessary to stop your service. blnStopThread=true; thdMain.Join(); } protected override void OnPause() { thdMain.Suspend(); } protected override void OnContinue() { thdMain.Resume(); } protected void WriteLog() { StreamWriter myWriter=null; do { Process.Start("net","send localhost yourValue"); try { myWriter=new StreamWriter("c:\\MyLog.txt",true); myWriter.WriteLine(DateTime.Now.ToString()); myWriter.Close(); } catch{}; Thread.Sleep(5000); }while(blnStopThread==false); } }} 
     WinSDemoIns.csusing System;using System.Collections;using System.ComponentModel;using System.Configuration.Install;using System.ServiceProcess;namespace WinSDemo{ /// <summary> /// Summary description for WinSDemoIns. /// </summary> [RunInstaller(true)] public class WinSDemoIns : System.Configuration.Install.Installer { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private ServiceInstaller serviceInstaller; private ServiceProcessInstaller processInstaller; public WinSDemoIns() { // This call is required by the Designer. InitializeComponent(); // TODO: Add any initialization after the InitComponent call processInstaller = new ServiceProcessInstaller(); serviceInstaller = new ServiceInstaller(); // Service will run under system account processInstaller.Account = ServiceAccount.LocalSystem; // Service will have Start Type of Manual serviceInstaller.StartType = ServiceStartMode.Manual; serviceInstaller.ServiceName = "MyTest"; Installers.Add(serviceInstaller); Installers.Add(processInstaller); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); } #endregion }}此外,需要添加引用System.ServiceProcess.Dll
      

  12.   

    http://www.fawcette.com/china/XmlFile.aspx?ID=260