Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using System.Collections;
- using System;
- using System.Net;
- using System.IO;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- public class LoginCore : MonoBehaviour {
- public string serverAddress = "127.0.0.1";
- public int serverPort = 32211;
- private TcpClient _client;
- private NetworkStream _stream;
- private Thread _thread;
- private byte[] _buffer = new byte[1024];
- private string receiveMsg = "";
- private bool isConnected = false;
- private bool connectionError = false;
- private float connectionTimer = 0.0f;
- void Start() {
- SetupConnection();
- }
- void OnApplicationQuit() {
- CloseConnection();
- }
- void OnGUI() {
- if(connectionError) {
- GUI.Label(new Rect(10,10,250,25), "Time to reconnect: "+connectionTimer.ToString()+" of 15 s");
- if(connectionTimer >= 15.0f) {
- connectionError = false;
- connectionTimer = 0.0f;
- SetupConnection();
- } else {
- connectionTimer += Time.deltaTime;
- }
- } else if(isConnected) {
- if(GUI.Button(new Rect(10,10,250,25), "LOGIN"))
- SendData("0x000/Testuser/Testpassword");
- }
- }
- private void SetupConnection() {
- try {
- _thread = new Thread(ReceiveData);
- _thread.IsBackground = true;
- _client = new TcpClient(serverAddress, serverPort);
- _stream = _client.GetStream();
- _thread.Start();
- isConnected = true;
- } catch (Exception e) {
- CloseConnection();
- connectionError = true;
- Debug.Log(e.ToString());
- }
- }
- private void ReceiveData() {
- if(!isConnected)
- return;
- int numberOfBytesRead = 0;
- while(isConnected && _stream.CanRead) {
- try {
- numberOfBytesRead = _stream.Read(_buffer, 0, _buffer.Length);
- receiveMsg = Encoding.ASCII.GetString(_buffer, 0, numberOfBytesRead);
- _stream.Flush();
- Debug.Log(receiveMsg);
- receiveMsg = "";
- } catch (Exception e) {
- CloseConnection();
- Debug.Log(e.ToString());
- }
- }
- }
- private void CloseConnection() {
- if(isConnected) {
- _thread.Interrupt();
- _stream.Close();
- _client.Close();
- isConnected = false;
- receiveMsg = "";
- }
- }
- private void SendData(string msgToSend) {
- byte[] bytesToSend = Encoding.ASCII.GetBytes(msgToSend);
- if(_stream.CanWrite)
- _stream.Write(bytesToSend, 0, bytesToSend.Length);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement