summaryrefslogtreecommitdiff
path: root/Valheim_v0.141.2_r202102/Valheim/assembly_valheim/ZConnector2.cs
blob: 06435472d049767285473d5ff141a03a0212615d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
using System;
using System.Net;
using System.Net.Sockets;

public class ZConnector2 : IDisposable
{
	private TcpClient m_socket;

	private IAsyncResult m_result;

	private IPEndPoint m_endPoint;

	private string m_host;

	private int m_port;

	private bool m_dnsError;

	private bool m_abort;

	private float m_timer;

	private static float m_timeout = 5f;

	public ZConnector2(string host, int port)
	{
		m_host = host;
		m_port = port;
		Dns.BeginGetHostEntry(host, OnHostLookupDone, null);
	}

	public void Dispose()
	{
		Close();
	}

	private void Close()
	{
		if (m_socket != null)
		{
			m_socket.Close();
			m_socket = null;
		}
		m_abort = true;
	}

	public bool IsPeer(string host, int port)
	{
		if (m_host == host && m_port == port)
		{
			return true;
		}
		return false;
	}

	public bool UpdateStatus(float dt, bool logErrors = false)
	{
		if (m_abort)
		{
			ZLog.Log("ZConnector - Abort");
			return true;
		}
		if (m_dnsError)
		{
			ZLog.Log("ZConnector - dns error");
			return true;
		}
		if (m_result != null && m_result.IsCompleted)
		{
			return true;
		}
		m_timer += dt;
		if (m_timer > m_timeout)
		{
			Close();
			return true;
		}
		return false;
	}

	public ZSocket2 Complete()
	{
		if (m_socket != null && m_socket.Connected)
		{
			ZSocket2 result = new ZSocket2(m_socket, m_host);
			m_socket = null;
			return result;
		}
		Close();
		return null;
	}

	public bool CompareEndPoint(IPEndPoint endpoint)
	{
		return m_endPoint.Equals(endpoint);
	}

	private void OnHostLookupDone(IAsyncResult res)
	{
		IPHostEntry iPHostEntry = Dns.EndGetHostEntry(res);
		if (m_abort)
		{
			ZLog.Log("Host lookup abort");
		}
		else if (iPHostEntry.AddressList.Length == 0)
		{
			m_dnsError = true;
			ZLog.Log("Host lookup adress list empty");
		}
		else
		{
			m_socket = ZSocket2.CreateSocket();
			m_result = m_socket.BeginConnect(iPHostEntry.AddressList, m_port, null, null);
		}
	}

	public string GetEndPointString()
	{
		return m_host + ":" + m_port;
	}

	public string GetHostName()
	{
		return m_host;
	}

	public int GetHostPort()
	{
		return m_port;
	}
}