方法 : ソケット リスナーを作成します。
[このドキュメントはプレビュー版であり、後のリリースで変更されることがあります。 空白のトピックは、プレースホルダーとして挿入されています。]
ソケット ベースのネットワーク通信をサポートする .NET Compact Framework します。 考慮事項については、.NET Compact Framework でのプログラミングのソケットに固有を参照してください ソケットのプログラミング。
次の使用例は、アプリケーションと、クライアント アプリケーションのインスタンスにサーバーのインスタンスを作成し、ソケット ベース接続を介して、2 つのアプリケーションの通信方法を示します。 localhost アドレスをサーバーの使用します。したがって、両方のアプリケーション クライアントで実行します。 サーバーのインスタンスは、クライアントがそのと通信できる前に実行されてされる必要があります。
ソケット接続経由で通信するには
Server Form を実装するという名前のクラスを作成し、クラスに次のコードを追加します。
Private Shared output AsString = ""PublicSubNew() EndSubPublicSub createListener() ' Create an instance of the TcpListener class.Dim tcpListener As TcpListener = NothingDim ipAddress As IPAddress = Dns.GetHostEntry("localhost").AddressList(0) Try ' Set the listener on the local IP address. ' and specify the port. tcpListener = New TcpListener(ipAddress, 13) tcpListener.Start() output = "Waiting for a connection..."Catch e As Exception output = "Error: " + e.ToString() MessageBox.Show(output) EndTryWhileTrue ' Always use a Sleep call in a while(true) loop ' to avoid locking up your CPU. Thread.Sleep(10) ' Create a TCP socket. ' If you ran this server on the desktop, you could use ' Socket socket = tcpListener.AcceptSocket() ' for greater flexibility.Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient() ' Read the data stream from the client.Dim bytes(255) AsByteDim stream As NetworkStream = tcpClient.GetStream() stream.Read(bytes, 0, bytes.Length) Dim helper AsNew SocketHelper() helper.processMsg(tcpClient, stream, bytes) EndWhileEndSubSharedSub Main() Application.Run(New Server()) EndSub
static string output = ""; public Server() { } publicvoid createListener() { // Create an instance of the TcpListener class. TcpListener tcpListener = null; IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0]; try { // Set the listener on the local IP address// and specify the port. tcpListener = new TcpListener(ipAddress, 13); tcpListener.Start(); output = "Waiting for a connection..."; } catch (Exception e) { output = "Error: " + e.ToString(); MessageBox.Show(output); } while (true) { // Always use a Sleep call in a while(true) loop// to avoid locking up your CPU. Thread.Sleep(10); // Create a TCP socket.// If you ran this server on the desktop, you could use// Socket socket = tcpListener.AcceptSocket()// for greater flexibility. TcpClient tcpClient = tcpListener.AcceptTcpClient(); // Read the data stream from the client.byte[] bytes = newbyte[256]; NetworkStream stream = tcpClient.GetStream(); stream.Read(bytes, 0, bytes.Length); SocketHelper helper = new SocketHelper(); helper.processMsg(tcpClient, stream, bytes); } } staticvoid Main() { Application.Run(new Server()); }
Server クラスで手段、サーバーを起動します。 たとえば、ボタンの createListener イベントで Click を呼び出します。
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Me.createListener() EndSub
private void button1_Click(object sender, EventArgs e) { this.createListener(); }
SocketHelper、という名前のクラスを作成し、クラスに次のコードを追加します。
Class SocketHelper Private mscClient As TcpClient Private mstrMessage AsStringPrivate mstrResponse AsStringPrivate bytesSent() AsBytePublicSub processMsg(ByVal client As TcpClient, ByVal stream As NetworkStream, ByVal bytesReceived() AsByte) ' Handle the message received and ' send a response back to the client. mstrMessage = Encoding.ASCII.GetString(bytesReceived, 0, bytesReceived.Length) mscClient = client mstrMessage = mstrMessage.Substring(0, 5) If mstrMessage.Equals("Hello") Then mstrResponse = "Goodbye"Else mstrResponse = "What?"EndIf bytesSent = Encoding.ASCII.GetBytes(mstrResponse) stream.Write(bytesSent, 0, bytesSent.Length) EndSubEndClass
class SocketHelper { TcpClient mscClient; string mstrMessage; string mstrResponse; byte[] bytesSent; publicvoid processMsg(TcpClient client, NetworkStream stream, byte[] bytesReceived) { // Handle the message received and // send a response back to the client. mstrMessage = Encoding.ASCII.GetString(bytesReceived, 0, bytesReceived.Length); mscClient = client; mstrMessage = mstrMessage.Substring(0, 5); if (mstrMessage.Equals("Hello")) { mstrResponse = "Goodbye"; } else { mstrResponse = "What?"; } bytesSent = Encoding.ASCII.GetBytes(mstrResponse); stream.Write(bytesSent, 0, bytesSent.Length); } }
サーバーは、クライアントに接続するときにこのクラスをインスタンス化します。
Client Form を実装するという名前のクラスを作成し、クラスに次のコードを追加します。
Shared Sub Connect(ByVal serverIP AsString, ByVal message AsString) Dim output AsString = ""Try ' Create a TcpClient. ' The client requires a TcpServer that is connected ' to the same address specified by the server and port ' combination.Dim port As Int32 = 13 Dim client AsNew TcpClient(serverIP, port) ' Translate the passed message into ASCII and store it as a byte array.Dim data(255) As [Byte] data = System.Text.Encoding.ASCII.GetBytes(message) ' Get a client stream for reading and writing. ' Stream stream = client.GetStream();Dim stream As NetworkStream = client.GetStream() ' Send the message to the connected TcpServer. stream.Write(data, 0, data.Length) output = "Sent: " + message MessageBox.Show(output) ' Buffer to store the response bytes. data = New [Byte](255) {} ' String to store the response ASCII representation.Dim responseData AsString = String.Empty ' Read the first batch of the TcpServer response bytes.Dim bytes As Int32 = stream.Read(data, 0, data.Length) responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes) output = "Received: " + responseData MessageBox.Show(output) ' Close everything. stream.Close() client.Close() Catch e As ArgumentNullException output = "ArgumentNullException: " + e.ToString() MessageBox.Show(output) Catch e As SocketException output = "SocketException: " + e.ToString() MessageBox.Show(output) EndTryEndSubSharedSub Main() Application.Run(New Client()) EndSub
public Client() { this.MinimizeBox = false; } staticvoid Connect(string serverIP, string message) { string output = ""; try { // Create a TcpClient.// The client requires a TcpServer that is connected// to the same address specified by the server and port// combination. Int32 port = 13; TcpClient client = new TcpClient(serverIP, port); // Translate the passed message into ASCII and store it as a byte array. Byte[] data = new Byte[256]; data = System.Text.Encoding.ASCII.GetBytes(message); // Get a client stream for reading and writing.// Stream stream = client.GetStream(); NetworkStream stream = client.GetStream(); // Send the message to the connected TcpServer. stream.Write(data, 0, data.Length); output = "Sent: " + message; MessageBox.Show(output); // Buffer to store the response bytes. data = new Byte[256]; // String to store the response ASCII representation. String responseData = String.Empty; // Read the first batch of the TcpServer response bytes. Int32 bytes = stream.Read(data, 0, data.Length); responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); output = "Received: " + responseData; MessageBox.Show(output); // Close everything. stream.Close(); client.Close(); } catch (ArgumentNullException e) { output = "ArgumentNullException: " + e; MessageBox.Show(output); } catch (SocketException e) { output = "SocketException: " + e.ToString(); MessageBox.Show(output); } } staticvoid Main() { Application.Run(new Client()); }
Client クラスで、ユーザーに、サーバーへの接続手段を提供します。 たとえば、ボタンの Connect イベントで、 Click メソッドを呼び出します。
Private Sub button1_Click(ByVal sender AsObject, ByVal e As EventArgs) ' In this code example, use a hard-coded ' IP address and message.Dim serverIP AsString = "localhost"Dim message AsString = "Hello" Connect(serverIP, message) EndSub
private void button1_Click(object sender, EventArgs e) { // In this code example, use a hard-coded// IP address and message.string serverIP = "localhost"; string message = "Hello"; Connect(serverIP, message); }
サーバーとクライアント アプリケーションをコンパイルします。
デバイスに両方のアプリケーションを展開します。
サーバー アプリケーション、デバイス上で実行し、サーバーを起動します。
クライアント アプリケーション、デバイス上で実行し、サーバーに接続します。
コードのコンパイル方法
クライアント プログラムでは、次の名前空間への参照が必要です。
サーバー プログラムには、次の名前空間への参照が必要です。