首先,这是我的代码:
public void requestLogin()
{
LoginRequest loginRequest = new LoginRequest { username = "matthew798", password = "test" };
//var ip = IPAddress.Parse("127.0.0.1");
//var ep = new IPEndPoint(ip, 4598);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.BeginConnect("127.0.0.1", 4598, new AsyncCallback(ConnectedCallback), client);
connectDone.WaitOne();
var sevenItems = new byte[] { 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20 };
byte[] byteData = Serializer.GetByteArray<LoginRequest>(loginRequest);
client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), client);
//Send(client, );
sendDone.WaitOne();
client.Shutdown(SocketShutdown.Both);
client.Disconnect(true);
if (client.Connected)
Debug.Log("We're still connnected");
else
Debug.Log("We're disconnected");
client.Close();
}
private void ConnectedCallback(IAsyncResult ar)
{
Socket client = (Socket)ar.AsyncState;
client.EndConnect(ar);
Debug.Log("Socket connected");
connectDone.Set();
}
private static void Send(Socket client, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), client);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", bytesSent);
// Signal that all bytes have been sent.
sendDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
它是C#中的套接字程序(它是统一项目的一部分)。当我调用requestLogin()
函数时,它会连接并发送数据ONCE。我在TCP服务器模式下使用herculese-utility。按下任何子请求按钮会导致客户端连接到服务器,但不会发送任何内容并引发以下异常:
SocketException: A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied