PHP作为客户端用套接字去连接C#的某个端口,只连接不发数据,需不需制订协议?
虽然能连接,但C#客户端这边太占CPU了
PHP代码如下:
PHP code
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$connection = socket_connect($socket, $IP, 2012);
C#代码如下:
namespace abcde
{
class abcSocket
{
public static StateObject state;
public IPAddress ipAddress;
public IPEndPoint localEndPoint;
public Socket serverSocket;
public static String receive;
public static String receive1;
public static int back;
public void ListenFlow()
{
ipAddress = IPAddress.Parse("0.0.0.0");
localEndPoint = new IPEndPoint(ipAddress,2000);
this.serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(localEndPoint);
serverSocket.Listen(100);
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), serverSocket);
}
public void AcceptCallback(IAsyncResult ar)
{
try
{
Socket serverSocket = (Socket)ar.AsyncState;
Socket clientSocket = serverSocket.EndAccept(ar);
state = new StateObject();
state.workSocket = clientSocket;
this.serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), this.serverSocket);
clientSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
public void ReadCallback(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket clientSocket = state.workSocket;//从异步状态对象中获得State对象和客户套接字
int bytesRead = clientSocket.EndReceive(ar);//从客户套接字读取数据
if (bytesRead > 0)
{
byte[] str = state.buffer;
back=Convert.ToInt32(str[0]);
receive = System.Text.Encoding.UTF8.GetString(str);
}
Thread.Sleep(1);
try { clientSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); }
catch (Exception e) { MessageBox.Show("因网络不稳定,已中断一个已有的链接"); }
byte[] str1 = state.buffer;
abcde.abcSocket.receive1 = Convert.ToString(str1[0]);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
public static void Send(String data)
{
byte[] byteData = Encoding.UTF8.GetBytes(data);
state.workSocket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), state.workSocket);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
Socket clientSocket = (Socket)ar