2016年2月16日火曜日

Windowsでプロセス間通信2(ソケット(UDP))

プロセス間通信をソケット(UDP)で行う場合のひな型

 送信側
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class SocketSend
{
  const string  address = "127.0.0.1";
  const int port = 5555;
  public static void Main()
  {
    //1.ソケット作成
    Socket soc = new Socket(AddressFamily.InterNetwork,
                            SocketType.Dgram,
                            ProtocolType.Udp);
    IPEndPoint ePoint = new IPEndPoint(IPAddress.Parse(address),port);
    while(true)
      {
        //2.処理
        Thread.Sleep(1000);
        //3.データ送信
        DateTime d = DateTime.Now;
        Encoding enc = Encoding.UTF8;
        byte[] sendData;
        sendData = enc.GetBytes(d.ToString());
        soc.SendTo(sendData,ePoint);
      }
    
  }
  
}

 受信側
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class Socketレエイヴェ
{
  const string  address = "127.0.0.1";
  const int port = 5555;
  public static void Main()
  {
    //1.ソケット作成
    Socket soc = new Socket(AddressFamily.InterNetwork,
                            SocketType.Dgram,
                            ProtocolType.Udp);

    EndPoint ePoint = new IPEndPoint(0,0);
    EndPoint bPoint = new IPEndPoint(0,port);
    byte[] rData = new byte[4096];
    int len;
    //2.ソケットのバインド
    soc.Bind(bPoint);
    while(true)

      {
        //2.データ受信
        len = soc.ReceiveFrom(rData,ref ePoint);
        Array.Resize(ref rData,len);
        Encoding enc = Encoding.UTF8;
        Console.WriteLine(enc.GetString(rData));
        //3.処理
        Thread.Sleep(1000);
        
      }
  }
}

0 件のコメント:

コメントを投稿