Skip to content

Instantly share code, notes, and snippets.

@reishisu
Created July 8, 2019 18:18
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/853cdca3de5c501bf500342a57588c44 to your computer and use it in GitHub Desktop.
Save reishisu/853cdca3de5c501bf500342a57588c44 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;
public class ChatClient : MonoBehaviour {
// ゲームオブジェクト
public InputField input_field;
public GameObject content;
public GameObject chat_log;
// サーバー情報
private string server_ip_address = "192.168.0.25";
private int port = 25252;
// クライアントの送信窓口
NetworkStream network_stream;
// 送信内容
private string send_text;
// 受信用
private float request_span = 10f;
private byte[] buffer = new byte[4096];
// Start is called before the first frame update
void Start() {
network_stream = new TcpClient(server_ip_address, port).GetStream();
Debug.Log(network_stream.Read(buffer, 0, buffer.Length));
network_stream.Close();
//Componentを扱えるようにする
input_field = input_field.GetComponent<InputField>();
}
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.Read(buffer, 0, buffer.Length);
string message = Encoding.UTF8.GetString(buffer);
GameObject instance = Instantiate(chat_log);
instance.transform.parent = content.transform;
instance.transform.localScale = new Vector3(1, 1, 1);
instance.GetComponent<Text>().text = message;
network_stream.Close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment