using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Net; using System.Net.Sockets; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Socket mySocket; NetworkStream myStream; StreamReader myReader; StreamWriter myWriter; private void button1_Click(object sender, EventArgs e) { IPHostEntry myHostEntry; IPAddress myAddress; int myPort; EndPoint myEndPoint; button1.Enabled = false; mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); myPrint("ソケットを作成しました"); //myHostEntry = Dns.GetHostEntry(textBox1.Text); //myAddress = myHostEntry.AddressList[0]; myAddress = IPAddress.Parse("192.168.1.3"); myPort = 55555; myEndPoint = new IPEndPoint(myAddress, myPort); mySocket.Connect(myEndPoint); myPrint("接続しました"); myStream = new NetworkStream(mySocket); myReader = new StreamReader(myStream, Encoding.UTF8); myWriter = new StreamWriter(myStream, Encoding.UTF8); myWriter.AutoFlush = true; button2.Enabled = true; button3.Enabled = true; } private void button3_Click(object sender, EventArgs e) { string mySendData; string myRecvData; mySendData = textBox2.Text; textBox2.Clear(); myWriter.WriteLine(mySendData); myPrint("送信<<" + mySendData); myRecvData = myReader.ReadLine(); myPrint("受信>>" + myRecvData); } private void button2_Click(object sender, EventArgs e) { button2.Enabled = false; button3.Enabled = false; mySocket.Shutdown(SocketShutdown.Send); myPrint("サーバーへの送信をシャットダウン"); if(mySocket.Poll(2000000, SelectMode.SelectRead)) myPrint("サーバーがシャットダウンを伝えてきました"); else myPrint("サーバーが応答しないので終了します"); myEndSession(); } public void myEndSession() { mySocket.Close(); myPrint("ソケットを閉じました"); button1.Enabled = true; button2.Enabled = false; button3.Enabled = false; } public void myPrint(string str) { listBox1.Items.Add(str); listBox1.TopIndex = listBox1.Items.Count - 1; listBox1.Refresh(); } } }