Answer the question
In order to leave comments, you need to log in
Tcp chat, how to fix duplicates?
Server code
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();
}
}
Answer the question
In order to leave comments, you need to log in
This is how it seems to work as it should, but it still seems to me that I'm doing it wrong
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);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question