C#でPC間の通信をAIにサンプル書いてもらいました。
実際に動作は確認してないですが、参考になれば。
PC側のFirewallだとか、
IPアドレス固定とか、
そういったものはちゃんと考えた方が良いです。
サーバー側
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
namespace con1
{
// ソケット通信(サーバー側)
class server1
{
static void Main()
{
IPAddress host1 = IPAddress.Parse("127.0.0.1");
int port1 = 8765;
IPEndPoint ipe1 = new IPEndPoint(host1, port1);
TcpListener server = null;
string recvline, sendline = null;
int num, i = 0;
Boolean outflg = false;
byte[] buf = new byte[1024];
Regex reg = new Regex("\0");
try
{
server = new TcpListener(ipe1);
Console.WriteLine("クライアントからの入力待ち状態");
server.Start();
while (true)
{
using (var client = server.AcceptTcpClient())
{
using (var stream = client.GetStream())
{
while ((i = stream.Read(buf, 0, buf.Length)) != 0)
{
recvline = reg.Replace(Encoding.UTF8.GetString(buf), "");
Console.WriteLine("client側の入力文字=" + recvline);
if (recvline == "bye")
{
outflg = true;
break;
}
try
{
num = int.Parse(recvline);
if (num % 2 == 0)
{
sendline = "OKです";
}
else
{
sendline = "NGです";
}
}
catch
{
sendline = "数値を入力して下さい";
}
finally
{
buf = Encoding.UTF8.GetBytes(sendline);
stream.Write(buf, 0, buf.Length);
Array.Clear(buf, 0, buf.Length);
}
}
}
}
if (outflg == true)
{
break;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
server.Stop();
Console.WriteLine("サーバー側終了です");
}
}
}
}
クライアント側
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace ClientSocketExample
{
class Program
{
static void Main()
{
// サーバーのIPアドレスとポート番号を設定
string serverIpAddress = "127.0.0.1"; // サーバーのIPアドレス
int serverPort = 8765; // サーバーのポート番号
try
{
// ソケットを作成
using (var clientSocket = new TcpClient())
{
// サーバーに接続
clientSocket.Connect(serverIpAddress, serverPort);
// メッセージを送信
string messageToSend = "Hello, server!";
byte[] sendData = Encoding.UTF8.GetBytes(messageToSend);
clientSocket.GetStream().Write(sendData, 0, sendData.Length);
// サーバーからの応答を受信
byte[] receiveData = new byte[1024];
int bytesRead = clientSocket.GetStream().Read(receiveData, 0, receiveData.Length);
string serverResponse = Encoding.UTF8.GetString(receiveData, 0, bytesRead);
Console.WriteLine("サーバーからの応答: " + serverResponse);
}
}
catch (Exception ex)
{
Console.WriteLine("エラー: " + ex.Message);
}
}
}
}
コメント
コメントを投稿