Skip to content

Instantly share code, notes, and snippets.

@noqisofon
Created December 17, 2010 08:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noqisofon/744659 to your computer and use it in GitHub Desktop.
Save noqisofon/744659 to your computer and use it in GitHub Desktop.
"How are you?" で始まる UDP 非同期通信。
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace demo.asyncudp.guest {
/// <summary>
///
/// </summary>
class AsyncUDPGuestSample {
/// <summary>
///
/// </summary>
/// <param name="ar"></param>
public void sendCompleted(IAsyncResult ar) {
messageSent = true;
}
/// <summary>
///
/// </summary>
/// <param name="ar"></param>
public void receiveCompleted(IAsyncResult ar) {
messageReceived = true;
}
/// <summary>
///
/// </summary>
/// <param name="args"></param>
public void run(string[] args) {
int listen_port = 2000;
//IPHostEntry host = Dns.GetHostEntry( Dns.GetHostName() );
//Stack<IPAddress> address_stack = new Stack<IPAddress>( host.AddressList );
//IPEndPoint remote_point = new IPEndPoint( address_stack.Pop(), listen_port );
// 受信から始めるときは、IP アドレスに Any(0.0.0.0) を入れておきます。
IPEndPoint listen_point = new IPEndPoint( IPAddress.Any, listen_port );
UdpClient client = new UdpClient( listen_point );
Encoding encoding = Encoding.UTF8;
string greeting = string.Empty;
string segment = string.Empty;
byte[] send_bytes = null;
int times = 0;
while ( true ) {
/*
* Guest は bob。
*/
Console.Write( "alice > " );
IAsyncResult done = client.BeginReceive( receiveCompleted, null );
while ( !messageReceived ) {
Thread.Sleep( 100 );
}
//segment = encoding.GetString( client.EndReceive( done, ref listen_point ) );
// listen_point には受信した IP アドレスとポート番号が入ります。
segment = encoding.GetString( client.EndReceive( done, ref listen_point ) );
Console.WriteLine( segment );
if ( segment.StartsWith( "bye" ) )
break;
Thread.Sleep( 1000 );
if ( segment.EndsWith( "How are you?" ) ) {
Random r = new Random();
int index = r.Next( CONDITIONS.Length );
greeting = string.Format( "{0} Thanks. How are you?", CONDITIONS[index] );
} else {
greeting = "over.";
}
Console.WriteLine( "bob < {0}", greeting );
send_bytes = encoding.GetBytes( greeting );
// 次に送信するときは、前に受信した IPEndPoint オブジェクトを指定します。
done = client.BeginSend( send_bytes, send_bytes.Length, listen_point, sendCompleted, null );
while ( !messageSent ) {
if ( times > 100 ) {
if ( !done.IsCompleted )
Console.WriteLine( "タイムアウトしました。" );
/*
* タイムアウトしたら、greeting を "bye." にして待機ループを終了します。
*/
greeting = "bye.";
break;
}
Thread.Sleep( 100 );
++times;
}
client.EndSend( done );
times = 0;
messageSent = false;
}
}
/// <summary>
///
/// </summary>
/// <param name="args"></param>
static void Main(string[] args) {
AsyncUDPGuestSample progn = new AsyncUDPGuestSample();
progn.run( args );
}
/// <summary>
///
/// </summary>
private static bool messageSent = false;
/// <summary>
///
/// </summary>
private static bool messageReceived = false;
/// <summary>
///
/// </summary>
static string[] CONDITIONS = new string[] { "Not bad.", "Good!", "Pretty Good!", "Great!" };
}
}
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace demo.asyncudp.client {
/// <summary>
///
/// </summary>
class AsyncUDPHostSample {
/// <summary>
///
/// </summary>
public AsyncUDPHostSample() {
IPHostEntry host = Dns.GetHostEntry( Dns.GetHostName() );
Stack<IPAddress> address_stack = new Stack<IPAddress>( host.AddressList );
this.remote_point_ = new IPEndPoint( address_stack.Pop(), 2000 );
}
/// <summary>
///
/// </summary>
/// <param name="ar"></param>
public void sendCompleted(IAsyncResult ar) {
UdpClient client = (UdpClient)ar.AsyncState;
//Console.WriteLine( " number of bytes sent: {0}", client.EndSend( ar ) );
messageSent = true;
}
/// <summary>
///
/// </summary>
public void receiveCompleted(IAsyncResult ar) {
messageReceived = true;
}
/// <summary>
///
/// </summary>
void run(string[] args) {
int times = 0;
UdpClient client = new UdpClient();
string greeting = "Hi, How are you?";
string segment = string.Empty;
Encoding encoding = Encoding.UTF8;
byte[] send_bytes = null;
IAsyncResult done = null;
client.Connect( remote_point_ );
while ( true ) {
Console.WriteLine( "alice < {0}", greeting );
send_bytes = encoding.GetBytes( greeting );
done = client.BeginSend( send_bytes, send_bytes.Length, sendCompleted, client );
while ( !messageSent ) {
if ( times > 300 ) {
if ( !done.IsCompleted )
Console.WriteLine( "タイムアウトしました。" );
/*
* タイムアウトしたら、greeting を "bye." にして待機ループを終了します。
*/
greeting = BYE;
break;
}
Thread.Sleep( 100 );
++times;
}
times = 0;
messageSent = false;
//if ( !done.CompletedSynchronously )
// greeting = BYE;
if ( greeting.StartsWith( "bye" ) )
break;
Thread.Sleep( 1000 );
done = client.BeginReceive( receiveCompleted, null );
Console.Write( "bob > " );
while ( !messageReceived ) {
Thread.Sleep( 100 );
}
segment = encoding.GetString( client.EndReceive( done, ref remote_point_ ) );
Console.WriteLine( segment );
if ( segment.EndsWith( "How are you?" ) ) {
Random r = new Random();
greeting = CONDITIONS[r.Next( CONDITIONS.Length )];
} else if ( segment.StartsWith( "over" ) ) {
greeting = BYE;
} else {
greeting = BYE;
}
messageReceived = false;
}
}
/// <summary>
///
/// </summary>
/// <param name="args"></param>
static void Main(string[] args) {
AsyncUDPHostSample progn = new AsyncUDPHostSample();
progn.run( args );
}
/// <summary>
///
/// </summary>
private static bool messageSent = false;
/// <summary>
///
/// </summary>
private static bool messageReceived = false;
/// <summary>
///
/// </summary>
private static readonly string[] CONDITIONS = new string [] { "Pretty Good!", "Great!", "Not bad.", "Good!" };
/// <summary>
///
/// </summary>
private static readonly string BYE = "bye.";
/// <summary>
///
/// </summary>
private IPEndPoint remote_point_;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment