Skip to content

Instantly share code, notes, and snippets.

@noqisofon
Created November 15, 2010 04:49
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/700057 to your computer and use it in GitHub Desktop.
Save noqisofon/700057 to your computer and use it in GitHub Desktop.
うにょうにょな TCP クライアント窓。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace sample.demo.tcpclient.app.widgets {
/// <summary>
///
/// </summary>
public partial class TCPClientDemoForm : Form {
/// <summary>
///
/// </summary>
public TCPClientDemoForm() {
InitializeComponent();
}
/// <summary>
///
/// </summary>
/// <param name="text"></param>
private void set_text_setter(string text) {
StringBuilder resulttext_builder = new StringBuilder( tbResult.Text );
resulttext_builder.AppendLine( text );
tbResult.Text = resulttext_builder.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="ergs"></param>
private void btnSend_Click(object sender, EventArgs ergs) {
TcpClient client = new TcpClient( AddressFamily.InterNetwork );
NetworkStream stream = null;
set_text_setter( "送信ボタンが押されました。" );
try {
IPAddress ip_address;
if ( tbDstIpAddress.Text == String.Empty ) {
IPHostEntry host = Dns.GetHostEntry( Dns.GetHostName() );
Stack<IPAddress> address_stack = new Stack<IPAddress>( host.AddressList );
// 0 番は IPv6 なので、IPv4 の IP アドレスにする。
ip_address = address_stack.Pop();
} else
ip_address = IPAddress.Parse( tbDstIpAddress.Text );
int port = Convert.ToInt32( tbDstPort.Text );
IPEndPoint endpoint = new IPEndPoint( ip_address, port );
client.Connect( endpoint );
stream = client.GetStream();
if ( stream.CanWrite ) {
string send_text = string.Format( "<request><get version=\"{0}\">/</get><host>{1}</host></request>",
1.1,
tbDstIpAddress.Text
);
byte[] send_bytes = Encoding.UTF8.GetBytes( send_text );
stream.Write( send_bytes, 0, send_bytes.Length );
}
if ( stream.CanRead ) {
client.ReceiveBufferSize = 256;
byte[] received_bytes = new byte[client.ReceiveBufferSize];
int received_bytes_amount;
string received_text = string.Empty;
received_bytes_amount = stream.Read( received_bytes, 0, received_bytes.Length );
received_text = Encoding.UTF8.GetString( received_bytes,
0,
received_bytes_amount
);
set_text_setter( received_text );
}
} catch ( ArgumentNullException ane ) {
MessageBox.Show( ane.ToString(), ane.Source );
} catch ( SocketException se ) {
MessageBox.Show( se.ToString(), se.Source );
} finally {
set_text_setter( "終了しました。" );
if ( stream != null )
stream.Close();
client.Close();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment