我目前正在开发一个需要使用TCP或Socket连接的项目。因为我给了一个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
答案 0 :(得分:2)
您应该使用http协议。检查维基百科文章中的示例会话:http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol。仅发送网址不足以让服务器做出响应。
看起来像这样:
REQUEST:
GET /index.html HTTP/1.1
Host: www.example.com
响应:
HTTP/1.1 200 OK
Date: Mon, 23 May 2005 22:38:34 GMT
Server: Apache/1.3.3.7 (Unix) (Red-Hat/Linux)
Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
Etag: "3f80f-1b6-3e1cb03b"
Content-Type: text/html; charset=UTF-8
Content-Length: 131
Connection: close
<html>
<head>
<title>An Example Page</title>
</head>
<body>
Hello World, this is a very simple HTML document.
</body>
</html>
您可以使用telnet检查您尝试发送的邮件是否正确。另一个选择是将您的链接粘贴到浏览器中,并使用Fiddler或Wireshark检查发送到服务器的内容。
<强>更新强>
例如,如果您更改代码的第一行,则应该从维基百科获得响应:
Host = "en.wikipedia.org";
string Datamsg = @"GET /wiki/Main_Page HTTP/1.1
Host: en.wikipedia.org
";
所以你的代码应该是这样的(我要离开你应该放置有效令牌的部分等):
Host = "member.sugacane.com";
string Datamsg = @"GET /userInfo?userid=2&token=SomeToken HTTP/1.1
Host: member.sugacane.com
";
答案 1 :(得分:0)
我想知道我发错了Datamsg
如果您要连接的服务器是HTTP服务器,那么是,您发送的请求不正确。为此,请使用HttpClient
或HttpWebRequest
等库。