初学网络编程的困惑

jknight 2003-10-19 09:45:39
vb里可以用socket控件。当有数据传到指定端口时会触发一个事件。
可是c#似乎是面向过程的编程了。要用while语句不断的查看是否有新信息。

下面2句节选自收发邮件的程序:
writeStream.Write(dataToSend,0,dataToSend.Length); //向服务器发送请求
receiveData = readStream.ReadLine(); //接受服务器返回的信息

为什么在这里不用while语句?万一程序执行到第二句时服务器的信息还没传过来呢?不是会发生错误吗?
...全文
43 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
jknight 2003-10-20
  • 打赏
  • 举报
回复
还是不太明白。最不能理解的是:

writeStream.Write(dataToSend,0,dataToSend.Length); //向服务器发送请求
receiveData = readStream.ReadLine(); //接受服务器返回的信息

为什么在这里不用while语句?万一程序执行到第二句时服务器的信息还没传过来呢?不是会发生错误吗?
aloxy 2003-10-19
  • 打赏
  • 举报
回复
示例
[Visual Basic, C#, C++] 下面的示例显示如何使用 Socket 类向 HTTP 服务器发送数据和接收响应。

[Visual Basic]
Imports System
Imports System.Text
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports Microsoft.VisualBasic



Public Class mySocket

Private Shared Function connectSocket(server As String, port As Integer) As Socket
Dim s As Socket = Nothing
Dim iphe As IPHostEntry = Nothing


Try
' Get host related information.
iphe = Dns.Resolve(server)


' Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
' an exception to be thrown if the host IP Address is not compatible with the address family
' (typical in the IPv6 case).
Dim ipad As IPAddress

For Each ipad In iphe.AddressList
Dim ipe As New IPEndPoint(ipad, port)

Dim tmpS As New Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp)

tmpS.Connect(ipe)

If tmpS.Connected Then
s = tmpS
Exit For
End If

Next ipad

Catch e As SocketException
Console.WriteLine("SocketException caught!!!")
Console.WriteLine(("Source : " + e.Source))
Console.WriteLine(("Message : " + e.Message))
Catch e As Exception
Console.WriteLine("Exception caught!!!")
Console.WriteLine(("Source : " + e.Source))
Console.WriteLine(("Message : " + e.Message))
End Try
Return s
End Function 'connectSocket



' This method requests the home page content for the passed server.
' It displays the number of bytes received and the page content.
Private Shared Function socketSendReceive(server As String, port As Integer) As String
'Set up variables and String to write to the server.
Dim ASCII As Encoding = Encoding.ASCII
Dim [Get] As String = "GET / HTTP/1.1" + ControlChars.Cr + ControlChars.Lf + "Host: " + server + ControlChars.Cr + ControlChars.Lf + "Connection: Close" + ControlChars.Cr + ControlChars.Lf + ControlChars.Cr + ControlChars.Lf
Dim ByteGet As [Byte]() = ASCII.GetBytes([Get])
Dim RecvBytes(255) As [Byte]
Dim strRetPage As [String] = Nothing

' Create a socket connection with the specified server and port.
Dim s As Socket = connectSocket(server, port)

If s Is Nothing Then
Return "Connection failed"
End If
' Send request to the server.
s.Send(ByteGet, ByteGet.Length, 0)


' Receive the server home page content.
Dim bytes As Int32 = s.Receive(RecvBytes, RecvBytes.Length, 0)



' Read the first 256 bytes.
strRetPage = "Default HTML page on " + server + ":" + ControlChars.Cr + ControlChars.Lf
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes)


While bytes > 0
bytes = s.Receive(RecvBytes, RecvBytes.Length, 0)
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes)
End While

Return strRetPage
End Function 'socketSendReceive

'Entry point which delegates to C-style main Private Function
Public Overloads Shared Sub Main()
Main(System.Environment.GetCommandLineArgs())
End Sub


Overloads Private Shared Sub Main(args() As String)
Dim host As String
Dim port As Integer = 80

If args.Length = 1 Then
' If no server name is passed as argument to this program, use the current
' host name as default.
host = Dns.GetHostName()
Else
host = args(1)
End If

Dim result As String = socketSendReceive(host, port)

Console.WriteLine(result)
End Sub 'Main
End Class 'mySocket

[C#]
using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;

public class mySocket
{
private static Socket connectSocket(string server, int port)
{
Socket s = null;
IPHostEntry iphe = null;


try
{
// Get host related information.
iphe = Dns.Resolve(server);


// Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
// an exception to be thrown if the host IP Address is not compatible with the address family
// (typical in the IPv6 case).
foreach(IPAddress ipad in iphe.AddressList)
{
IPEndPoint ipe = new IPEndPoint(ipad, port);

Socket tmpS =
new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

tmpS.Connect(ipe);

if(tmpS.Connected)
{
s = tmpS;
break;
}
else
continue;
}
}

catch(SocketException e)
{
Console.WriteLine("SocketException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(Exception e)
{
Console.WriteLine("Exception caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
return s;

}


// This method requests the home page content for the passed server.
// It displays the number of bytes received and the page content.
private static string socketSendReceive(string server, int port)
{
//Set up variables and String to write to the server.
Encoding ASCII = Encoding.ASCII;
string Get = "GET / HTTP/1.1\r\nHost: " + server +
"\r\nConnection: Close\r\n\r\n";
Byte[] ByteGet = ASCII.GetBytes(Get);
Byte[] RecvBytes = new Byte[256];
String strRetPage = null;

// Create a socket connection with the specified server and port.
Socket s = connectSocket(server, port);

if (s == null)
return ("Connection failed");

// Send request to the server.
s.Send(ByteGet, ByteGet.Length, 0);


// Receive the server home page content.
Int32 bytes = s.Receive(RecvBytes, RecvBytes.Length, 0);



// Read the first 256 bytes.
strRetPage = "Default HTML page on " + server + ":\r\n";
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);


while (bytes > 0)
{
bytes = s.Receive(RecvBytes, RecvBytes.Length, 0);
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
}

return strRetPage;
}

public static void Main(string[] args)
{
string host;
int port = 80;

if (args.Length == 0)
// If no server name is passed as argument to this program, use the current
// host name as default.
host = Dns.GetHostName();
else
host = args[0];


string result = socketSendReceive(host, port);

Console.WriteLine(result);
}

}
rgbcn 2003-10-19
  • 打赏
  • 举报
回复


例子讲的很清楚
ms-help://MS.VSCC/MS.MSDNVS/cpguide/html/cpconsocketcodeexamples.htm




using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

// State object for receiving data from remote device.
public class StateObject {
public Socket workSocket = null; // Client socket.
public const int BufferSize = 256; // Size of receive buffer.
public byte[] buffer = new byte[BufferSize]; // Receive buffer.
public StringBuilder sb = new StringBuilder();// Received data string.
}

public class AsynchronousClient {
// The port number for the remote device.
private const int port = 11000;

// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone =
new ManualResetEvent(false);
private static ManualResetEvent sendDone =
new ManualResetEvent(false);
private static ManualResetEvent receiveDone =
new ManualResetEvent(false);

// The response from the remote device.
private static String response = String.Empty;

private static void StartClient() {
// Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
// "host.contoso.com" is the name of the
// remote device.
IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

// Create a TCP/IP socket.
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);

// Connect to the remote endpoint.
client.BeginConnect( remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();

// Send test data to the remote device.
Send(client,"This is a test<EOF>");
sendDone.WaitOne();

// Receive the response from the remote device.
Receive(client);
receiveDone.WaitOne();

// Write the response to the console.
Console.WriteLine("Response received : {0}", response);

// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();

} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}

private static void ConnectCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the state object.
Socket client = (Socket) ar.AsyncState;

// Complete the connection.
client.EndConnect(ar);

Console.WriteLine("Socket connected to {0}",
client.RemoteEndPoint.ToString());

// Signal that the connection has been made.
connectDone.Set();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}

private static void Receive(Socket client) {
try {
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;

// Begin receiving the data from the remote device.
client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}

private static void ReceiveCallback( IAsyncResult ar ) {
try {
// Retrieve the state object and the client socket
// from the async state object.
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocket;

// Read data from the remote device.
int bytesRead = client.EndReceive(ar);

if (bytesRead > 0) {
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));

// Get the rest of the data.
client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
new AsyncCallback(ReceiveCallback), state);
} else {
// All the data has arrived; put it in response.
if (state.sb.Length > 1) {
response = state.sb.ToString();
}
// Signal that all bytes have been received.
receiveDone.Set();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}

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());
}
}

public static int Main(String[] args) {
StartClient();
return 0;
}
}
本书主要是冲着实际应用而来的,共分11章。在刚开始的第一章就详细地讲解了Java开发环境的搭建、反编译工具的使用、JDK文档资料的查阅,Java程序的编译、运行过程。在第二章中,全面地讲解Java的基本语法知识,对基本语法的讲解也不是泛泛而谈,而是在其中贯穿各种实际应用中的巧妙用法和注意事项。在第三章和第四章中,透彻系统地讲解了面向对象的思想和应用。在以后的章节中,用通俗易懂的手法,紧密联系实际应用的方式,深入浅出地讲解了多线程,常用Java类,Java中的I/O(输入输出)编程,GUI与Applet,网络编程等方面的知识。 本书许多内容都来源于程序员圈子里的非正式交流,或源于某些成功的案例与作者的经验、心得,但这些东西对新手来说,是很难自学到的。作者从事了多年的软件开发和培训教学,非常清楚那些容易使新手困惑的问题,在学习过程中会碰到的拦路虎,作者结合了多年实际开发与教学经验,收集了众多学员在学习中常提到的问题,对平时讲课的内容进行了精心整理。读者从本书中不仅可以学习到Java本身方面的知识,还能学到了许多编程思想和实际操作手法,仿佛老手就在你面前进行现场演示一样。本书不仅全面的介绍了Java语言本身,最重要还交会读者去掌握编程思想,找到编程感觉,而不是死记硬背语言本身,书中涉及到的应用问题分析,远远超了一个Java程序员在学习和应用Java过程中所有可能碰到的问题。 本书不仅讲概念,讲怎么做,还告诉读者为什么;不仅讲操作技能,还贯穿一些系统的理论,这样读者才不至于不明不白,或是似乎明白,但不知道具体该怎么干。本书一步步引导读者深入,使读者轻松愉快、兴趣盎然、水到渠成、潜移默化地掌握Java编程及许多其他的软件开发思想。 本书语言流畅,内容翔实,分析透彻,是一本适合广大计算机编程爱好者的优秀读物。本书结构合理,图文并茂,实用性强,适合于广大有经验的开发人员来迅速转换到Java语言,对广大初学计算机编程语言的爱好者来说,这本书就是非常好的切入点。本书基本理论知识完备,又紧密联系实际开发,也非常适合作为大专院校师生的教学与学习用书,将给广大师生带来一种革命性的教学方式与学习思路,令人耳目一新。 这不是一本参考资料和Java百科全书,不是什么"宝典"和"大全",但却可以让新手变为老手,相信学完此书,再看任何以前看不懂的Java书都会显得非常轻松。即使是很有经验的老手,也能从本书中有巨大收益。如果你想非常轻松就精通Java编程,并期望学完便能参加实际的开发工作,本书就是你非常好的一个选择。

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧