初学网络编程的困惑

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

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

为什么在这里不用while语句?万一程序执行到第二句时服务器的信息还没传过来呢?不是会发生错误吗?
...全文
41 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;
}
}

110,530

社区成员

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

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

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