You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
2.1 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace connor_zwcadm.util {
class SocketUtil {
public static string SendRequest(string function, string param = "") {
if (string.IsNullOrEmpty(function)) {
return null;
}
SocketClient client = new SocketClient(9192);
string inputInfo = function+ ":" + param;
return client.StartClient(inputInfo);
}
public class SocketClient {
private string _ip = string.Empty;
private int _port = 0;
private Socket _socket = null;
private byte[] buffer = new byte[1024 * 1024 * 2];
public SocketClient(string ip, int port) {
this._ip = ip;
this._port = port;
}
public SocketClient(int port) {
this._ip = "127.0.0.1";
this._port = port;
}
public string StartClient(string inputInfo) {
string resp = null;
try {
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress address = IPAddress.Parse(_ip);
IPEndPoint endPoint = new IPEndPoint(address, _port);
_socket.Connect(endPoint);
_socket.Send(Encoding.UTF8.GetBytes(inputInfo));
KUtil.Log("向服务发送的消息 [{0}]", inputInfo);
_socket.Shutdown(SocketShutdown.Send);
int length = _socket.Receive(buffer);
resp = Encoding.UTF8.GetString(buffer, 0, length);
KUtil.Log("接收服务器消息 [{0}]", resp);
}
catch (Exception ex) {
KUtil.LogErr(ex);
}
finally {
try {
_socket.Shutdown(SocketShutdown.Both);
}
catch (Exception) {
}
try {
_socket.Close();
}
catch (Exception) {
}
}
return resp;
}
}
}
}