using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Web;
using System.Web.Services;
namespace LockerService
{
/// <summary>
/// WebService 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释以下行。
// [System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
static WebService()
{
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);
clientSocket.Connect(ipe);
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
public static Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public static string host = ConfigurationManager.AppSettings["ip"];
public static int port = int.Parse(ConfigurationManager.AppSettings["port"]);
[WebMethod]
public void Open(string sendStr)
{
try
{
SendCommand(sendStr);
}
catch
{
OpenLink();
}
}
public void OpenLink()
{
try
{
clientSocket.Dispose();
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);
clientSocket.Connect(ipe);
}
catch (Exception ex)
{
OpenLink();
}
}
/// <summary>
/// 发送指令
/// </summary>
/// <param name="number"></param>
public void SendCommand(string sendStr)
{
//send message
byte[] sendBytes = strToToHexByte(sendStr);
clientSocket.Send(sendBytes);
}
/// <summary>
/// 字符串转换16进制byte数组
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
private static byte[] strToToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);
return returnBytes;
}
#region 写文件
/// <summary>
/// 写文件
/// </summary>
/// <param name="Path">文件路径</param>
/// <param name="Strings">文件内容</param>
public void WriteFile(string FileFullPath, string Strings)
{
if (!System.IO.File.Exists(FileFullPath))
{
System.IO.FileStream fs = System.IO.File.Create(FileFullPath);
fs.Close();
}
System.IO.StreamWriter sw = new System.IO.StreamWriter(FileFullPath, false, System.Text.Encoding.GetEncoding("gb2312"));
sw.Write(Strings);
sw.Flush();
sw.Close();
sw.Dispose();
}
#endregion
}
}