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 {
不麻烦,我都忘了放在哪台机器上了(我有三台机器)客户端代码,屏蔽的是为了做试验 这段代码服务器端不用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
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
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;
}
}
}
}
}
不清楚你在说什么???看看题目啊!哪里有webservice这几个字
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();
关闭这个客户端的套接字
:)
这段代码服务器端不用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
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