C# SOCKET 问题

large_small 2005-03-23 12:07:37
高手请看下面的代码为什么不能执行啊?会报出参数有误的错误
这可是从MSDN里copy出来的

static void Main(string[] args)
{
//
// TODO: 在此处添加代码以启动应用程序
//
IPHostEntry lipa = Dns.Resolve("localhost");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 5151);

Socket s = new Socket(lep.Address.AddressFamily,
SocketType.Dgram,
ProtocolType.Udp);


try
{


// Creates an IpEndPoint to capture the identity of the sending host.
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint tempRemoteEP = (EndPoint)sender;



// Creates a byte buffer to receive the message.
byte[] buffer = new byte[1024];
// Receives datagram from a remote host. This call blocks.
s.ReceiveFrom(buffer,0,100,SocketFlags.None, ref tempRemoteEP);

// Displays the information received to the screen.
Console.WriteLine(" I received the following message : " +
Encoding.ASCII.GetString(buffer) );

}
catch(Exception e)
{
Console.WriteLine("Exception : " + e.ToString() );
}
}
...全文
123 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
conan19771130 2005-03-25
  • 打赏
  • 举报
回复
using System.Net.Sockets;
using System.Threading;


namespace com.zggps
{
/// <summary>
/// SocketClient 的摘要说明。
/// </summary>
public class SocketClient
{
private Socket m_clientSocket;
private int m_nServerPort;
private string m_strServerIP;
private int BufferSize = 1409;
public int BUFFERSIZE
{
get
{
return BufferSize;
}
set
{
BufferSize=value;
}
}
// ManualResetEvent instances signal completion.
private ManualResetEvent connectDone =
new ManualResetEvent(false);
private ManualResetEvent sendDone =
new ManualResetEvent(false);
private ManualResetEvent receiveDone =
new ManualResetEvent(false);

public delegate void OnReceiveMsg(byte[] data);
public event OnReceiveMsg ReceiveMsg;

public delegate void OnConnected();
public event OnConnected Connected;

public delegate void OnDisConnected();
public event OnDisConnected DisConnected;

public delegate void OnSendBack();
public event OnSendBack SendBack;

public delegate void OnError(string msg);
public event OnError ReportError;

private System.Threading.Thread m_mianThread;

private bool m_bConnected=false;

public bool IsConnect
{
get
{
return m_bConnected;
}
set
{
this.m_bConnected = value;
}
}
/// <summary>
/// 创建对象
/// </summary>
/// <param name="strServerIP">Server IP Address</param>
/// <param name="nPort">Server Port</param>
public SocketClient(string strServerIP,int nPort)
{
this.m_strServerIP = strServerIP;
this.m_nServerPort = nPort;
}

/// <summary>
/// Start the client socket
/// </summary>
public void Begin()
{
System.Threading.ThreadStart ts=new ThreadStart(this.StartClient);
this.m_mianThread = new Thread(ts);
this.m_mianThread.Start();
}

/// <summary>
/// 清除正在使用的资源
/// </summary>
public void Dispose()
{
if(this.m_clientSocket.Connected)
{
this.m_clientSocket.Shutdown(SocketShutdown.Both);
this.m_clientSocket.Close();
}
if(this.m_mianThread.IsAlive)
this.m_mianThread.Abort();
}

private void StartClient()
{
// Connect to a remote device.
try
{
IPHostEntry ipHostInfo = Dns.Resolve(this.m_strServerIP);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, this.m_nServerPort);

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

// Connect to the remote endpoint.
this.m_clientSocket.BeginConnect( remoteEP,
new AsyncCallback(ConnectCallback), this.m_clientSocket);
}
catch (Exception e)
{
this.ReportError("StartClient found a error:\r\n" + e.ToString());
}
}

private void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket) ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
this.m_bConnected = true;
this.Connected();
Receive(client);

}
catch (Exception e)
{
this.ReportError("连接到远程服务器失败,请检查网络连接,错误内容如下:\r\n"+e.ToString());
this.m_bConnected =false;
}
}

/// <summary>
/// 关闭连接
/// </summary>
public void close()
{
try
{
if(m_clientSocket.Connected)
{
this.m_clientSocket.Shutdown(SocketShutdown.Both);
this.m_clientSocket.Close();
}
}
catch(Exception e)
{
this.ReportError("Close Client Error:" + e.ToString());
}
finally
{
this.m_bConnected = false;
}
}

private void Receive(Socket client)
{
try
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;
state.buffer=new byte[BufferSize];
// Begin receiving the data from the remote device.
client.BeginReceive( state.buffer, 0, BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
this.ReportError("Begin Receive found a error:\r\n" + e.ToString());
}
}

protected void ReceiveCallback( IAsyncResult ar )
{
try
{
// Retrieve the state object and the client socket
// from the asynchronous 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)
{
byte[] data=new byte[bytesRead];
for(int i=0;i<bytesRead;i++)
{
data[i]=state.buffer[i];
}
this.ReceiveMsg(data);
// Get the rest of the data.
client.BeginReceive(state.buffer,0,BufferSize,0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
this.DisConnected();
this.close();
}
}
catch
{
//this.ReportError("Receive msg found a error:\r\n" + e.ToString());
this.close();
this.DisConnected();
}
}

/// <summary>
/// 发送信息到服务器
/// </summary>
/// <param name="data">信息内容</param>
public void Send(byte[] data)
{
try
{
if(this.m_clientSocket.Connected)
this.m_clientSocket.BeginSend(data,0,data.Length,0,
new AsyncCallback(SendCallback),this.m_clientSocket);
else
{
this.ReportError("发送信息错误,连接已经断开");
}
}
catch
{
this.ReportError("发送信息错误");
this.close();
}
}

private 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 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);
this.SendBack();
}
catch (Exception e)
{
ReportError(e.ToString());
}
}
}

// State object for receiving data from remote device.
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Receive buffer.
public byte[] buffer;
}
}
conan19771130 2005-03-23
  • 打赏
  • 举报
回复
那一行,出什么错

110,532

社区成员

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

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

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