我目前正在做一个需要使用 TCP 或 Socket 连接的项目。因为我给了一个 URL 让我连接到它,服务器会将数据推送给我。
给定的 URL 是http://member.sugacane.com/userInfo?userid=2&token=SomeToken
我通过 MSDN ( http://msdn.microsoft.com/en-us/library/kb5kfec7.aspx ) 并获取一些示例代码来处理它。
public static void StartClient(string Host, string token, int userID, int port)
{
Host = "member.sugacane.com";
string Datamsg = "userid=2&token=SomeToken";
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
try
{
// uses port 80.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostEntry(Host).HostName);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
string isConnect = "Socket connected to {0}" +sender.RemoteEndPoint.ToString();
// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes(Datamsg);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
string res = Encoding.ASCII.GetString(bytes, 0, bytesRec);
Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
我可以使用此代码连接到服务器,但我无法得到任何响应,字节始终为 0,它应该返回一些 XML 数据。我想知道是我发送错误Datamsg