サンプル集  >  C#  >  TcpClient
TcpClient
2014/03/19

System.Net.Sockets.TcpClientを使って文字列の通信をしてみます。

◆環境
OS Windows 7 Professional Service Pack 1 64bit
C# Microsoft Visual C# 2010 01018-587-4054044-70237

[ファイル]-[新規作成]-[プロジェクト]を選択。

[コンソール アプリケーション]を選択し、名前に「TcpServerTest」と入力し「OK」。

まずはサーバー側を作ります。 サーバー側はクライアント側から文字列を受信し、それを表示するようにしました。

Program.cs
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
41: 
42: 
43: 
44: 
45: 
46: 
47: 
48: 
49: 
50: 
51: 
52: 
53: 
54: 
55: 
56: 
57: 
58: 
59: 
60: 
61: 
62: 
63: 
64: 
65: 
66: 
67: 
68: 
69: 
70: 
71: 
72: 
73: 
74: 
75: 
76: 
77: 
78: 
79: 
80: 
81: 
82: 
83: 
84: 
85: 
86: 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TcpServerTest
{
    class Program
    {
        static void Main( string[] args )
        {
            Console.Write( "input ip:" );
            string ip = Console.ReadLine();

            Console.Write( "input port:" );
            string port = Console.ReadLine();

            System.Net.IPAddress ipAddr
            = System.Net.Dns.GetHostEntry( ip ).AddressList[0];

            // TcpListener生成
            System.Net.Sockets.TcpListener listener
            = new System.Net.Sockets.TcpListener( ipAddr
                                                , int.Parse( port )
                                                );

            // TCPクライアントからの接続要求を待てる状態にする
            listener.Start();
            Console.WriteLine( "listen successful." );
            Console.WriteLine( "IP=[{0}] Port=[{1}]"
                             , ( ( System.Net.IPEndPoint )
                                 listener.LocalEndpoint
                               ).Address
                             , ( ( System.Net.IPEndPoint )
                                 listener.LocalEndpoint
                               ).Port
                             );

            // TCPクライアントからの接続要求を受け付ける
            System.Net.Sockets.TcpClient client
            = listener.AcceptTcpClient();
            Console.WriteLine( "accepted connection {0} ({1})"
                             , ( ( System.Net.IPEndPoint )
                                 client.Client.LocalEndPoint
                               ).Address
                             , ( ( System.Net.IPEndPoint )
                                 client.Client.LocalEndPoint
                               ).Port
                             );

            // NetworkStream取得
            System.Net.Sockets.NetworkStream ns
            = client.GetStream();

            // データ受信
            System.Text.Encoding enc
            = System.Text.Encoding.UTF8;
            System.IO.MemoryStream ms
            = new System.IO.MemoryStream();
            byte[] data = new byte[256];
            int iRet = 0;
            do
            {
                iRet = ns.Read( data, 0, data.Length );
                if ( iRet == 0 )
                {
                    break;
                }
                ms.Write( data, 0, iRet );
            }
            while ( ns.DataAvailable );

            string msg = enc.GetString( ms.ToArray() );
            ms.Close();
            Console.WriteLine( "Read=[{0}]", msg );

            ns.Close();
            Console.WriteLine( "NetworkStream Close." );

            listener.Stop();
            Console.WriteLine( "TcpListener Stop." );

            Console.ReadLine();
        }
    }
}

続いてクライアント側を作ります。 クライアント側はサーバーへ接続後、文字列を送信するようにしました。

Program.cs
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
36: 
37: 
38: 
39: 
40: 
41: 
42: 
43: 
44: 
45: 
46: 
47: 
48: 
49: 
50: 
51: 
52: 
53: 
54: 
55: 
56: 
57: 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TcpClientTest
{
    class Program
    {
        static void Main( string[] args )
        {
            Console.Write("input ip:");
            string ip = Console.ReadLine();

            Console.Write("input port:");
            string port = Console.ReadLine();

            // サーバに接続
            System.Net.Sockets.TcpClient client
            = new System.Net.Sockets.TcpClient( ip
                                              , int.Parse( port )
                                              );
            Console.WriteLine("{0}:{1}に接続しました。{2}:{3}"
                             , ( ( System.Net.IPEndPoint )
                                 client.Client.RemoteEndPoint
                               ).Address
                             , ( ( System.Net.IPEndPoint )
                                 client.Client.RemoteEndPoint
                               ).Port
                             , ( ( System.Net.IPEndPoint )
                                 client.Client.LocalEndPoint
                               ).Address
                             , ( ( System.Net.IPEndPoint )
                                 client.Client.LocalEndPoint
                               ).Port
                             );

            // NetworkStream取得
            System.Net.Sockets.NetworkStream ns
            = client.GetStream();

            // 送信
            Console.Write("input message:");
            string msg = Console.ReadLine();

            System.Text.Encoding enc = System.Text.Encoding.UTF8;
            byte[] data = enc.GetBytes( msg );

            ns.Write( data, 0, data.Length );

            ns.Close();
            Console.WriteLine("NetworkStream Close.");

            Console.ReadLine();
        }
    }
}

コマンドプロンプトを起動し、サーバー側を先に動かし、IPアドレスとポートの入力を行います。

◆サーバー側
>TcpServerTest.exe
input ip:localhost
input port:12345
listen successful.
IP=[::1] Port=[12345]

コマンドプロンプトをもう一つ起動し、クライアント側を動かし、IPアドレスとポートの入力を行います。 うまくサーバーに接続できると、メッセージの入力待ちになります。

◆クライアント側
>TcpClientTest.exe
input ip:localhost
input port:12345
::1:12345に接続しました。::1:52615
input message:

サーバー側では接続を受け付けたメッセージが表示されます。

◆サーバー側
accepted connection ::1 (12345)

クライアント側でメッセージを入力すると、メッセージ送信後、クライアントは終了しました。

◆クライアント側
input message:Hello TcpClient!!
NetworkStream Close.

サーバー側はメッセージを受信し、受信したメッセージを表示して終了しました。

◆サーバー側
Read=[Hello TcpClient!!]
NetworkStream Close.
TcpListener Stop.

TcpClientを使う場合、サーバー側もIPアドレスが必要になるようです。

▲ PageTop  ■ Home


Copyright (C) 2014 ymlib.com