Advertisement
Guest User

Untitled

a guest
Jul 19th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. using System.Net.Sockets;
  7. using System.Text;
  8. using System.Net;
  9. using System.Threading.Tasks;
  10.  
  11. public class ChatClient : MonoBehaviour {
  12.  
  13. // ゲームオブジェクト
  14. public InputField input_field;
  15. public GameObject content;
  16. public GameObject chat_log;
  17.  
  18. // サーバー情報
  19. private string server_ip_address = "192.168.0.25";
  20. private int port = 25252;
  21.  
  22. // クライアントの送信窓口
  23. NetworkStream network_stream;
  24.  
  25. // 送信内容
  26. private string send_text;
  27.  
  28. // 受信用
  29. private float request_span = 10f;
  30. private byte[] buffer = new byte[4096];
  31.  
  32.  
  33. // Start is called before the first frame update
  34. void Start() {
  35.  
  36. network_stream = new TcpClient(server_ip_address, port).GetStream();
  37. Debug.Log(network_stream.Read(buffer, 0, buffer.Length));
  38. network_stream.Close();
  39.  
  40. //Componentを扱えるようにする
  41. input_field = input_field.GetComponent<InputField>();
  42. }
  43.  
  44. public void InputText() {
  45. //テキストにinputFieldの内容を反映
  46. send_text = input_field.text;
  47. }
  48.  
  49. // ボタンクリック時
  50. public void NetworkRequest() {
  51. // 接続要求
  52. network_stream = new TcpClient(server_ip_address, port).GetStream();
  53.  
  54. // 送信の内容をセット
  55. if (send_text.Length == 0) return;
  56. byte[] send_string = Encoding.UTF8.GetBytes(send_text);
  57.  
  58. // データを送信
  59. network_stream.Write(send_string, 0, send_string.Length);
  60.  
  61. // データを受信
  62. network_stream.Read(buffer, 0, buffer.Length);
  63. string message = Encoding.UTF8.GetString(buffer);
  64. GameObject instance = Instantiate(chat_log);
  65. instance.transform.parent = content.transform;
  66. instance.transform.localScale = new Vector3(1, 1, 1);
  67. instance.GetComponent<Text>().text = message;
  68.  
  69. network_stream.Close();
  70. }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement