udp&socket的问题!一天半没搞定!
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
private string server="127.0.0.1";
private Int32 port = 80;
private string message="GET / HTTP/1.1\r\nHost:127.0.0.1\r\nConnection: Close\r\n\r\n";//Hello, Net World!!!";
private Socket s;
private IPEndPoint ipep;
private Byte[] rvbuf=new Byte[1024];
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
new Class1().Start();
}
public void Start()
{
IPHostEntry iphe=Dns.Resolve(server);
ipep=new IPEndPoint(iphe.AddressList[0],port);
s=new Socket(ipep.AddressFamily,SocketType.Dgram,ProtocolType.Udp);
s.Connect(ipep);
Console.WriteLine("Connected!");
new Thread(new ThreadStart(this.Receive)).Start();
for(int i=0;i<10000;i++)
{
}
new Thread(new ThreadStart(this.Send)).Start();
Console.Read();
}
public void Receive()
{
try
{
byte[] d=new byte[1024];
s.BeginReceive(rvbuf,0,1024,SocketFlags.None,new AsyncCallback(Received),0);
}
catch(SocketException e)
{
Console.WriteLine(e.ToString());
}
}
public void Received(IAsyncResult iar)
{
/* for(int i=0;i<rvbuf.Length;i++)
{
Console.Write(rvbuf[i]);
}
*/
Console.WriteLine(Encoding.ASCII.GetString(rvbuf));
Console.WriteLine("\nReceived!");
}
public void Send()
{
try
{
s.Send(Encoding.ASCII.GetBytes(message),SocketFlags.None);
Console.WriteLine(message+" Sended!");
}
catch(SocketException e)
{
Console.WriteLine(e.ToString());
}
}
/* [STAThread]
static void Main(string[] args)
{
UdpClient udpClient = new UdpClient();
try
{
udpClient.Connect("localhost", 11000);
// Sends a message to the host to which you have connected.
Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");
udpClient.Send(sendBytes, sendBytes.Length);
// Sends a message to a different host using optional hostname and port parameters.
UdpClient udpClientB = new UdpClient();
udpClientB.Send(sendBytes, sendBytes.Length,"localhost", 11000);
//IPEndPoint object will allow us to read datagrams sent from any source.
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
// Blocks until a message returns on this socket from a remote host.
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
// Uses the IPEndPoint object to determine which of these two hosts responded.
Console.WriteLine("This is the message you received " +
returnData.ToString());
Console.WriteLine("This message was sent from " +
RemoteIpEndPoint.Address.ToString() +
" on their port number " +
RemoteIpEndPoint.Port.ToString());
udpClient.Close();
udpClientB.Close();
}
catch (Exception e )
{
Console.WriteLine(e.ToString());
}
Console.Read();
}
*/
}
}
里面是两个程序,都搞不定了,弟兄姊妹们,帮忙!!!