private void serverThread()
{
var tcpListener = new TcpListener(IPAddress.Any, 8080);
tcpListener.Start();
while (true)
{
var tcpClient = tcpListener.AcceptTcpClient();
Collections.listConnectedClients.Add(tcpClient);
byte[] data = new byte[256];
StringBuilder response = new StringBuilder();
NetworkStream stream = tcpClient.GetStream();
do
{
int bytes = stream.Read(data, 0, data.Length);
response.Append(Encoding.Unicode.GetString(data, 0, bytes));
}
while (stream.DataAvailable);
string ip = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString();
string name = response.ToString();
MessageBox.Show(name);
this.Invoke((MethodInvoker)(() =>
{
ListViewItem item = new ListViewItem(new string[] { ip, name });
lvOnlineUser.Items.Add(item);
}));
}
}
private void connect()
{
try
{
using (var tcpClient = new TcpClient())
{
tcpClient.Connect(address, port);
while (true)
{
if (!IsConnected(tcpClient))
{
break;
}
NetworkStream stream = tcpClient.GetStream();
byte[] msg = System.Text.Encoding.Unicode.GetBytes("Alex");
stream.Write(msg, 0, msg.Length);
}
connect();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
connect();
}
}
private void connect()
{
try
{
using (var tcpClient = new TcpClient())
{
tcpClient.Connect(address, port);
SendName(tcpClient);
while (true)
{
if (!IsConnected(tcpClient))
{
tcpClient.Close();
connect();
}
}
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
connect();
}
}
private void SendName(TcpClient client)
{
NetworkStream stream = client.GetStream();
byte[] msg = System.Text.Encoding.Unicode.GetBytes("Alex");
if (IsConnected(client))
{
stream.Write(msg, 0, msg.Length);
}
}