C# Client-Server: Only one client receives data - c#

I'm trying to debug this but it's getting super messy in my head, I really need a little help over here. I'm doing the classic Chat Application program with multiple clients and a server. What I have so far :
Clients connect to the server;
The server stores each client in a list;
When a client sends a message, it is then sent to all the clients in the list;
My problem is about this third step, on my server side, my program outputs the step correctly.
For example, if my user is Hugo and he sends Hey:
Sending hugo: hey
to System.Net.Sockets.TcpClient0
Sending hugo: hey
to System.Net.Sockets.TcpClient1
The message is redirected to all the Users connected to my server. Now the problem is on the Client Side, for some reasons, the message are displayed only on the LAST connected user. Considering the previous example, the message "Hey" would be displayed two times on TcpClient1 , and never on TcpClient0
Server code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections;
using ConsoleApp1;
namespace ServerSide
{
class Server
{
private int port;
private byte[] buffer = new byte[1024];
public delegate void DisplayInvoker(string t);
private StringBuilder msgclient = new StringBuilder();
private TcpListener client;
static IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
private IPAddress ipAddress = host.AddressList[0];
private TcpClient myclient;
private List<TcpClient> usersConnected = new List<TcpClient>();
public Server(int port)
{
this.port = port;
}
public void startServer()
{
client = new TcpListener(ipAddress, port);
client.Start();
SERV a = new SERV();
a.Visible = true;
a.textBox1.AppendText("Waiting for a new connection...");
while (true)
{
myclient = client.AcceptTcpClient();
usersConnected.Add(myclient);
a.textBox1.AppendText("New User connected #" + myclient.ToString() );
myclient.GetStream().BeginRead(buffer, 0, 1024, Receive, null);
a.textBox1.AppendText("Size of List " + usersConnected.Count);
}
}
private void Receive(IAsyncResult ar)
{
int intCount;
try
{
lock (myclient.GetStream())
intCount = myclient.GetStream().EndRead(ar);
if (intCount < 1)
{
return;
}
Console.WriteLine("MESSAGE RECEIVED " + intCount);
BuildString(buffer, 0, intCount);
lock (myclient.GetStream())
myclient.GetStream().BeginRead(buffer, 0, 1024, Receive, null);
}
catch (Exception e)
{
return;
}
}
public void Send(string Data)
{
lock (myclient.GetStream())
{
System.IO.StreamWriter w = new System.IO.StreamWriter(myclient.GetStream());
w.Write(Data);
w.Flush();
}
}
private void BuildString(byte[] buffer, int offset, int count)
{
int intIndex;
for (intIndex = offset; intIndex <= (offset + (count - 1)); intIndex++)
{
msgclient.Append((char)buffer[intIndex]);
}
OnLineReceived(msgclient.ToString());
msgclient.Length = 0;
}
private void OnLineReceived(string Data)
{
int i = 0;
foreach (TcpClient objClient in usersConnected)
{
Console.WriteLine("Sending " + Data + " to " + objClient + i);
Send(Data);
i++;
}
}
}
}
Client code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace WindowsFormsApp2
{
public partial class Form2 : Form
{
private delegate void DisplayInvoker(string t);
private string currentTopic = null;
private StringBuilder msg = new StringBuilder();
static public string MyUser { get; set; }
static private byte[] buffer = new byte[1024];
static IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
static IPAddress ipAddress = host.AddressList[0];
static Client user = new Client(MyUser, ipAddress, 136);
public Form2(string User) // when a user is logged in , directly connect him to the server
{
InitializeComponent();
MyUser = User;
user.clientConnection();
Thread readingg = new Thread(reading);
readingg.Start();
user.sendText(MyUser + " joined the chatroom!" +"\n");
IPAdress.Text = GetLocalIP(host);
IPAdress.ReadOnly = true;
}
public void reading()
{
user.getClient().GetStream().BeginRead(buffer, 0, 1024, ReadFlow, null);
Console.WriteLine("READING FUNCTION TRIGGERED FOR "+MyUser);
}
private void DisplayText(string t)
{
UserChat.AppendText(t);
Console.WriteLine("DISPLAY FUNCTION TRIGGERED FOR " + MyUser + "with " +msg.ToString());
}
private void BuildString(byte[] buffer,int offset, int count)
{
int intIndex;
for(intIndex = offset; intIndex <= (offset + (count - 1)); intIndex++)
{
if (buffer[intIndex] == 10)
{
msg.Append("\n");
object[] #params = { msg.ToString() };
Console.WriteLine("BUILDSTIRNG FUNCTION TRIGGERED FOR " + MyUser);
Invoke(new DisplayInvoker(DisplayText),#params);
msg.Length = 0;
}
else
{
msg.Append((char)buffer[intIndex]);
}
}
}
private void ReadFlow(IAsyncResult ar)
{
int intCount;
try
{
intCount = user.getClient().GetStream().EndRead(ar);
Console.WriteLine(intCount);
if (intCount < 1)
{
return;
}
Console.WriteLine(MyUser + "received a message");
BuildString(buffer, 0, intCount);
user.getClient().GetStream().BeginRead(buffer, 0, 1024, this.ReadFlow, null);
}catch(Exception e)
{
return;
}
}
private string GetLocalIP(IPHostEntry host)
{
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
return "192.168.1.1";
} // get your local ip
private void label1_(object sender, EventArgs e)
{
this.Text = "Hello " + MyUser;
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void UserMessage_TextChanged(object sender, EventArgs e)
{
}
private void UserMessage_Focus(object sender, EventArgs e)
{
UserMessage.Text = "";
}
private void UserMessage_Focus2(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
listBox1.Items.Add(addTopic.Text);
addTopic.Text = "Add Topic";
}
private void button2_(object sender, EventArgs e)
{
}
private void addTopic_(object sender, EventArgs e)
{
}
private void addTopic_TextChanged(object sender, EventArgs e)
{
}
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
string curItem = listBox1.SelectedItem.ToString();
label1.Text = "Topic "+curItem;
currentTopic = curItem;
}
private void IPAdress_TextChanged(object sender, EventArgs e)
{
}
// send msg to the server
private void UserChat_TextChanged(object sender, EventArgs e)
{
}
private void Form2_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
//Handle event here
System.Windows.Forms.Application.Exit();
}
private void Send_Click_1(object sender, EventArgs e)
{
user.sendText(MyUser + ": " + UserMessage.Text +"\n");
UserMessage.Text = " ";
}//send message
}
}

In OnLineReceived, for each client you call SendData, where you send to myclient. You probably want to pass objClient into SendData, and send to that.
Note that there are also some threading problems there; if someone connects exactly while you are iterating the list, it'll break the iterator, for example.

Related

I can't connect to a websocket server as a client in unity

I try to connect but it never ends up connecting. It doesn't show me any error, am I putting in the wrong place the data? Do I have to configure something in Unity?
I'm using SocketIoClient c# for the client. The server uses laravel and PHP
I suspect that I'm setting wring the SocketIOOptions. Already tried other 2 plugins, and none of them worked.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using SocketIOClient;
class Program : MonoBehaviour
{
public static Program instance = null;
async void Start()
{
Debug.Log("start code");
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(gameObject);
}
DontDestroyOnLoad(gameObject);
await Main();
}
public async Task Main()
{
Debug.Log("start main");
var uri = new Uri("ws://ws.testing.bet:6781");
var socket = new SocketIO(uri, new SocketIOOptions
{
ConnectionTimeout = TimeSpan.FromSeconds(120),
Query = new Dictionary<string, string>
{
{"key", "12356"},
{"cluster", "mt1"},
{"forceTLS", "true"},
{"enabledTransports", "ws,wss"}
},
});;
socket.OnConnected += Socket_OnConnected;
socket.OnPing += Socket_OnPing;
socket.OnPong += Socket_OnPong;
socket.OnDisconnected += Socket_OnDisconnected;
socket.OnReconnectAttempt += Socket_OnReconnecting;
socket.OnError += Socket_OnError;
socket.OnAny((name, response) =>
{
Debug.Log(name);
Debug.Log(response);
});
socket.On("RealTimeEvent", response =>
{
Debug.Log("Message: " + response.GetValue<string>());
});
await socket.ConnectAsync();
Debug.Log("TRYING");
}
private static void Socket_OnReconnecting(object sender, int e)
{
Debug.Log($"{DateTime.Now} Reconnecting: attempt = {e}");
}
private static void Socket_OnError(object sender, string e)
{
Debug.Log("Error: " + e);
}
private static void Socket_OnDisconnected(object sender, string e)
{
Debug.Log("disconnect: " + e);
}
private static async void Socket_OnConnected(object sender, EventArgs e)
{
Debug.Log("Socket_OnConnected");
var socket = sender as SocketIO;
Debug.Log("Socket.Id:" + socket.Id);
await socket.EmitAsync("hi", DateTime.Now.ToString());
}
private static void Socket_OnPing(object sender, EventArgs e)
{
Debug.Log("Ping");
}
private static void Socket_OnPong(object sender, TimeSpan e)
{
Debug.Log("Pong: " + e.TotalMilliseconds);
}
}

How do I fix "Operation not allowed on unconnected sockets"?

For a school project, I have to create a simple desktop chat app. I've gone for a client-server approach. After doing some research on TCP listeners and clients and following a few tutorials I produced the following code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace NetworkTest
{
public partial class Form1 : Form
{
private TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public string recieve;
public string TextToSend;
public Form1()
{
InitializeComponent();
IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName());
foreach(IPAddress address in localIP)
{
if(address.AddressFamily == AddressFamily.InterNetwork)
{
IPBox1.Text = address.ToString();
}
}
}
private void StartButton_Click(object sender, EventArgs e)
{
TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(PortBox1.Text));
listener.Start();
client = listener.AcceptTcpClient();
STR = new StreamReader(client.GetStream());
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker2.WorkerSupportsCancellation = true;
}
private void ConnectButton_Click(object sender, EventArgs e)
{
client = new TcpClient();
IPEndPoint IpEnd = new IPEndPoint(IPAddress.Parse(IPBox2.Text), int.Parse(PortBox2.Text));
try
{
ChatScreenBox.AppendText("Connect to Server" + "\n");
STW = new StreamWriter(client.GetStream());
STR = new StreamReader(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker2.WorkerSupportsCancellation = true;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (client.Connected)
{
try
{
recieve = STR.ReadLine();
this.ChatScreenBox.Invoke(new MethodInvoker(delegate ()
{
ChatScreenBox.AppendText("You: " + recieve + "\n");
}));
recieve = "";
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
if (client.Connected)
{
STW.WriteLine(TextToSend);
this.ChatScreenBox.Invoke(new MethodInvoker(delegate()
{
ChatScreenBox.AppendText("Me: " + TextToSend + "\n");
}));
}
else
{
MessageBox.Show("Sending Failed");
}
backgroundWorker2.CancelAsync();
}
private void SendButton_Click(object sender, EventArgs e)
{
if(MessageTextBox.Text != "")
{
TextToSend = MessageTextBox.Text;
backgroundWorker2.RunWorkerAsync();
}
MessageTextBox.Text = "";
}
}
}
UI: https://ibb.co/jk2HRcJ
In theory it should work however as soon as I try to send a message I get the alert "Operation not allowed on unconnected sockets".
Why is this? And how can I resolve this issue?
Thank you in advance
.
As the error says, you must create a connection before you can operate on it.
For socket, I once wrote a detailed sample tutorial, you can refer to it.
If you have any questions about this,please comment bellow and I'll check it out.

Tcp client Server C#

I work on tcp client and server application. I have found in youtube this code. There are no have problem connection with tcp client and server, when i send to message it repeat infinity messagebox like you:you:you:you:.How can i fix this problem? The codes uses backgroundWorker ,it can cause repeat message. Can i solve the problem using Thread class ?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
private TcpClient client;
public StreamReader STR;
public StreamWriter STW;
public string recieve;
public String TextToSend;
public Form1()
{
InitializeComponent();
IPAddress[] localIP = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress address in localIP)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
textBoxServerIP.Text = address.ToString();
}
}
}
private void buttonStart_Click(object sender, EventArgs e)
{
TcpListener listener = new TcpListener(IPAddress.Any, int.Parse(textBoxServerPort.Text));
listener.Start();
client = listener.AcceptTcpClient();
STR = new StreamReader(client.GetStream());
STW = new StreamWriter(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker2.WorkerSupportsCancellation = true;
}
private void buttonConnect_Click(object sender, EventArgs e)
{
client = new TcpClient();
IPEndPoint IpEnd = new IPEndPoint(IPAddress.Parse(textBoxClientIP.Text), int.Parse(textBoxClientPort.Text));
try
{
client.Connect(IpEnd);
if (client.Connected)
{
textBoxChatScreen.AppendText("Connected to server" + "\n");
STW = new StreamWriter(client.GetStream());
STR = new StreamReader(client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker2.WorkerSupportsCancellation = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (client.Connected)
{
try
{
recieve = STR.ReadLine();
this.textBoxChatScreen.Invoke(new MethodInvoker(delegate ()
{
textBoxChatScreen.AppendText("You:" + recieve + "\n");
}));
recieve = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
{
if (client.Connected)
{
STW.WriteLine (TextToSend);
this.textBoxChatScreen.Invoke(new MethodInvoker(delegate ()
{
textBoxChatScreen.AppendText("Me:" + TextToSend + "\n");
}));
}
else
{
MessageBox.Show("Sending failed");
}
backgroundWorker2.CancelAsync();
}
private void buttonSend_Click(object sender, EventArgs e)
{
if (textBoxMessage.Text != "")
{
TextToSend = textBoxMessage.Text;
backgroundWorker2.RunWorkerAsync();
}
textBoxMessage.Text = "";
}
}
}
I tried the code I can't run from the youtube video below.
https://www.youtube.com/watch?v=X16IyNbcAr0

C# Pcap.net communication

I would like to ask why is my communicator receiving sent frames. I'm trying to fix this problem using flag PacketDeviceOpenAttributes.NoCaptureLocal for receiving communicator but I'm still receiving sent frames. Could anyone know how to fix this problem? Thank you. Here is my code:
using PcapDotNet.Core;
using PcapDotNet.Packets;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PSIP
{
public partial class Form2 : Form
{
private Packet packet;
private List<Packet> buffer;
private IList<LivePacketDevice> allDevices;
private LivePacketDevice selectedDevice, sendDevice;
private int pkt_cnt;
private Thread thrReceive,thrSend;
public Form2(LivePacketDevice device)
{
InitializeComponent();
Show();
selectedDevice = device;
pkt_cnt = 0;
buffer = new List<Packet>();
allDevices = LivePacketDevice.AllLocalMachine;
for (int i = 0; i != allDevices.Count; ++i)
{
LivePacketDevice tempDevice = allDevices[i];
if (device.Description != null)
{
ListViewItem row = new ListViewItem(tempDevice.Name);
listDevices.Items.Add(row);
}
}
}
private void PacketHandler(object obj)
{
throw new NotImplementedException();
}
private void PacketHandler(Packet packet)
{
ListViewItem itemPacket = new ListViewItem(pkt_cnt.ToString());
itemPacket.SubItems.Add(packet.Ethernet.Destination.ToString());
itemPacket.SubItems.Add(packet.Ethernet.Source.ToString());
pktView.Items.Add(itemPacket);
buffer.Add(packet);
pkt_cnt++;
}
private void Sending()
{
for (int i = 0; i <= allDevices.Count; ++i)
{
sendDevice = allDevices[i];
if (sendDevice.Name.Equals(listDevices.SelectedItems[0].Text))
{
i = allDevices.Count;
}
}
using (PacketCommunicator communicator = sendDevice
.Open(100, PacketDeviceOpenAttributes.Promiscuous | PacketDeviceOpenAttributes.NoCaptureLocal, 1000))
{
int index = Int32.Parse(pktView.SelectedItems[0].Text);
Packet tmpPacket = buffer.ElementAt(index);
communicator.SendPacket(tmpPacket);
}
}
private void Receiving()
{
int c = int.Parse(packetcount.Text);
using (PacketCommunicator communicator = selectedDevice.Open(65536,
PacketDeviceOpenAttributes.NoCaptureRemote | PacketDeviceOpenAttributes.Promiscuous, 1000))
{
communicator.ReceivePackets(c, PacketHandler);
}
}
private void button1_Click(object sender, EventArgs e)
{
thrReceive = new Thread(Receiving);
thrReceive.Start();
}
private void buttonSend_Click(object sender, EventArgs e)
{
thrSend = new Thread(Sending);
thrSend.Start();
}
private void pktView_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
int index = Int32.Parse(pktView.SelectedItems[0].Text);
Packet tmpPacket = buffer.ElementAt(index);
textPacket.ResetText();
textPacket.AppendText(tmpPacket.Ethernet.ToHexadecimalString());
}
catch (Exception E)
{
Console.WriteLine(E.ToString());
}
}
private void buttonClear_Click(object sender, EventArgs e)
{
pktView.Items.Clear();
buffer.Clear();
pkt_cnt = 0;
}
} }
You seem to be using different PacketCommunicators, one for sending and one for receiving.
The documentation for NoCaptureRemote states "Defines if the local adapter will capture its own generated traffic.".
Since you're using two different communicators, the receiving communicator captures the sending communicator.

chatting by socket and C#

I did an application of chat with socket:
the server create a socket connection and wait message from any client
for Server:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
namespace server
{
public partial class Form1 : Form
{
public static byte[] data;
public static byte[] data1;
public static Socket sock;
public delegate void operation(string s);
public delegate void operation2();
public delegate bool verifier();
public Form1()
{
InitializeComponent();
sock = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPAddress adress = IPAddress.Parse("127.0.0.1");
IPEndPoint iep = new IPEndPoint(adress, 4000);
EndPoint ep = (EndPoint)iep;
sock.Bind(iep);
sock.Listen(10);
sock = sock.Accept();
data1 = new byte[1024];
data = new byte[1024];
Thread.Sleep(2000);
this.Show();
if (sock.Receive(data) > 0)
{
Thread t = new Thread(new ThreadStart(aller));
t.Start();
}
}
private void effectuer(String s)
{
textBox1.Text += "serveur: " + s + "\r\n";
message.Text = "";
}
private void effectuer4(String s)
{
textBox1.Text += "Client: " + s + "\r\n";
message.Text = "";
}
private void aller() {
String s = ASCIIEncoding.ASCII.GetString(data);
if (this.InvokeRequired) Invoke((operation)effectuer4, s);
else effectuer4(s);
//Thread.Sleep(2000);
byte[] data2 = new byte[1024];
if (sock.Receive(data2) > 0 && data2 != data)
{
data = data2;
Thread t = new Thread(new ThreadStart(aller));
t.Start();
}
}
private void buttonDisconnect_Click(object sender, EventArgs e)
{
sock.Close();
Application.Exit();
}
private void buttonSend_Click(object sender, EventArgs e)
{
String s = message.Text ;
data1 = System.Text.Encoding.ASCII.GetBytes(s);
sock.Send(data1);
Invoke((operation)effectuer, s);
}
}
}
For client : he send an empty message to server and wait for the response of server
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Net;
using System.Xml;
namespace client
{
public partial class Form1 : Form
{
public static TcpClient SocketPourClient = null;
public static string ClientMessage;
public static string ServerMessage;
Socket sock;
public static byte[] data;
public static byte[] data1;
public delegate void operation(String s);
public delegate void lancer();
public delegate bool verifier();
public Form1(string ip, int port)
{
InitializeComponent();
IPAddress adress = IPAddress.Parse("127.0.0.1");
IPEndPoint ipEnd = new IPEndPoint(adress, 4000);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
sock.Connect(ipEnd);
}
catch (SocketException e)
{
MessageBox.Show(e.ToString());
sock.Close();
}
Thread t1 = new Thread(envoi);
t1.Start();
data = new byte[1024];
if (sock.Receive(data) > 0)
{
Thread t=new Thread(new ThreadStart(aller));
t.Start();
}
}
private void aller()
{
String s = ASCIIEncoding.ASCII.GetString(data);
if(this.InvokeRequired) Invoke((operation)effectuer4, s);
else effectuer4(s);
// Thread.Sleep(2000);
byte[] data2 = new byte[1024];
if (sock.Receive(data2) > 0 && data2 != data)
{
data = data2;
Thread t = new Thread(new ThreadStart(aller));
t.Start();
}
}
private void envoi()
{
String s = message.Text ;
data1 = System.Text.Encoding.ASCII.GetBytes(s);
sock.Send(data1);
effectuer(s);
}
private void effectuer(String s)
{
textBox1.Text += "client: " + s + "\r\n";
message.Text = "";
}
private void effectuer4(String s)
{
textBox1.Text += "Server: " + s + "\r\n";
message.Text = "";
}
private void buttonDisconnect_Click(object sender, EventArgs e)
{
sock.Close();
Application.Exit();
}
private void buttonSend_Click_1(object sender, EventArgs e)
{
String s = message.Text ;
data1 = System.Text.Encoding.ASCII.GetBytes(s);
sock.Send(data1);
Invoke((operation)effectuer, s);
}
}
}
my problems are:
i won't that the server or client will be not obliged to initialise the application but twice can do it + when i did the server as a console application it works but when i changes the server to winforms like that the application is blocked!!!!!! So i need help
Don't run the listen/accept loop in the Form1 ctor!!
Run the listen/accept in a separate listening thread.

Categories