Skip to content

Instantly share code, notes, and snippets.

@reishisu
Created July 9, 2019 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reishisu/3f73502ab2319129139939f2585cae37 to your computer and use it in GitHub Desktop.
Save reishisu/3f73502ab2319129139939f2585cae37 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using UnityEngine.UI;
using System.Net.Sockets;
using System.Text;
using System.Net;
using System.Threading.Tasks;
using System.Threading;
public class ChatClient : MonoBehaviour {
// ゲームオブジェクト
public InputField input_field;
public GameObject content;
public GameObject chat_log;
public static string a;
//おまじない
private SynchronizationContext context;
// サーバー情報
private string server_ip_address = "192.168.0.25";
private int port = 25252;
// クライアントの送信窓口
NetworkStream network_stream;
// 送信内容
private string send_text;
// 受信用
private TcpListener listener;
private float request_span = 10f;
private byte[] buffer = new byte[4096];
// Start is called before the first frame update
void Start() {
context = SynchronizationContext.Current;
//Componentを扱えるようにする
input_field = input_field.GetComponent<InputField>();
// 監視
Task.Run(Listener);
}
private void Update() {
if (a != "") {
GameObject instance = Instantiate(chat_log);
instance.transform.parent = content.transform;
instance.transform.localScale = new Vector3(1, 1, 1);
instance.GetComponent<Text>().text = a;
a = "";
}
}
public void InputText() {
//テキストにinputFieldの内容を反映
send_text = input_field.text;
}
// ボタンクリック時
public void NetworkRequest() {
// 接続要求
network_stream = new TcpClient(server_ip_address, port).GetStream();
// 送信の内容をセット
if (send_text.Length == 0) return;
byte[] send_string = Encoding.UTF8.GetBytes(send_text);
// データを送信
network_stream.Write(send_string, 0, send_string.Length);
network_stream.Close();
}
public void Listener() {
SynchronizationContext.SetSynchronizationContext(context);
listener = new TcpListener(IPAddress.Any, port);
Debug.Log("監視開始1");
try {
listener.Start();
}
catch (Exception e) {
Debug.Log(e.Message);
Debug.Log(e.TargetSite);
Debug.Log(e.StackTrace);
}
Debug.Log("監視開始2");
while (true) {
//接続要求があったら受け入れる
TcpClient client = listener.AcceptTcpClient();
Debug.Log("きた!");
network_stream = client.GetStream();
// データを受信
network_stream.Read(buffer, 0, buffer.Length);
string message = Encoding.UTF8.GetString(buffer);
Debug.Log(message);
a = message;
// バッファリセット
buffer = new byte[4096];
network_stream.Close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment