TCP サーバー - Himeyama/Unity_memo GitHub Wiki

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
using System.Net;  
using System.Net.Sockets;  
using System.Text;


public class NewBehaviourScript : MonoBehaviour{
    public string ipAddress;
    public int port = 8088;
    public static long n;
    public long ln;

    private TcpListener listener;
    private TcpClient client;

    void Start(){
        IPAddress ip = IPAddress.Any; //IPAddress.Parse(ipAddress);
        listener = new TcpListener(ip, port);
        listener.Start();
        listener.BeginAcceptSocket(DoAcceptTcpClientCallback, listener);
    }

    void DoAcceptTcpClientCallback(IAsyncResult ar){
        TcpListener listener = (TcpListener)ar.AsyncState;
        client = listener.EndAcceptTcpClient(ar);
        Debug.Log("Connect: " + client.Client.RemoteEndPoint);
        NetworkStream stream = client.GetStream();
        StreamReader reader = new StreamReader(stream, Encoding.UTF8);
        while (client.Connected){
            while (!reader.EndOfStream){
                string str = reader.ReadLine();
                ln = n = long.Parse(str);
                Debug.Log(str);
            }

            if (client.Client.Poll(1000, SelectMode.SelectRead) && (client.Client.Available == 0)){
                Debug.Log("切断: " + client.Client.RemoteEndPoint);
                client.Close();
                break;
            }
        }
    }

    void OnApplicationQuit(){
        if(listener != null) listener.Stop();
        if(client != null) client.Close();
    }
}