AndroidとWindowsをTCPで通信させたいと思ったのですが、ぴったりなサンプルが無かったので。。
下記を参考にしています。
Java
Javaソケット通信入門。TCPでデータの送受信をする
C#
https://itsakura.com/csharp-socket
サーバー側(Java)
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 |
import java.io.*; import java.net.*; public class server { public static void main(String[] args) { // ----------------------------------------- // 1.TCPポートを指定してサーバソケットを作成 // ----------------------------------------- try (ServerSocket server = new ServerSocket(8765)) { while (true) { try { // ----------------------------------------- // 2.クライアントからの接続を待ち受け(accept) // ----------------------------------------- Socket sc = server.accept(); System.out.println(sc.getInetAddress() + "から接続を受付ました"); BufferedReader reader = null; // ----------------------------------------- // 3.クライアントからの接続ごとにスレッドで通信処理を実行 // ----------------------------------------- try { // クライアントからの受取用 reader = new BufferedReader(new InputStreamReader(sc.getInputStream())); String line = null; // クライアントから送信されたメッセージを取得 line = reader.readLine(); System.out.println("クライアントからのメッセージ=" + line); } catch (Exception e) { e.printStackTrace(); } finally { // リソースの解放 if (reader != null) reader.close(); if (sc != null) sc.close(); } } catch (Exception ex) { ex.printStackTrace(); break; } } } catch (Exception e) { e.printStackTrace(); } } } |
クライアント側(C#)
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 |
using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Text.RegularExpressions; namespace con2 { // ソケット通信(クライアント側) class client1 { static void Main() { IPAddress host1 = IPAddress.Parse("127.0.0.1"); int port1 = 8765; IPEndPoint ipe1 = new IPEndPoint(host1, port1); string line = ""; byte[] buf1 = new byte[1024]; Regex reg = new Regex("\0"); try { while (line != "bye") { using (var client = new TcpClient()) { client.Connect(ipe1); using (var stream = client.GetStream()) { // 標準入力からデータを取得 Console.WriteLine("--------------------------"); Console.WriteLine("送信する文字列を入力してください"); Console.WriteLine("--------------------------"); // サーバに送信 line = Console.ReadLine(); buf1 = Encoding.UTF8.GetBytes(line); stream.Write(buf1, 0, buf1.Length); } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Console.WriteLine("クライアント側終了です"); } } } } |
コンパイル方法
サーバー側
1 |
javac server.java |
クライアント側
csc.exeのパスは各自の環境に合わせること。
1 |
C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe client1.cs |