Dear All Developer,
I am newbie at this field.My task is creat a multi-client and single server chart app using C#. This app, which allow server to reply the message from client to client who send the message at one form. I was trying to figured this example
Multithreaded Chat Server[
^] .
but, in my project, if more than one client connected to this server, i just able send the data to the last client who connected to this server. In my case, my purpose is this server must be able send the data to the client which i selected.
What I have tried:
this is my code in form1.cs
using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;
namespace serverchat
{
public partial class Form1 : Form
{
private int count;
Dictionary<string, TcpClient> clientDict;
List<TcpClient> clientList;
private TcpListener tcpServer;
private TcpClient tcpClient;
private Thread th;
private ArrayList formArray = new ArrayList();
private ArrayList threadArray = new ArrayList();
public delegate void ChangedEventHandler(object sender, EventArgs e);
public event ChangedEventHandler Changed;
public delegate void SetListBoxItem(String str, String type);
private TcpClient client;
private NetworkStream clientStream;
public delegate void SetTextCallback(string s);
public TcpClient connectedClient
{
get { return client; }
set { client = value; }
}
public Form1()
{
InitializeComponent();
Changed += new ChangedEventHandler(ClientAdded);
TreeNode node;
node = tvClientList.Nodes.Add("list client");
}
public void StartServer()
{
tbPort.Enabled = false;
th = new Thread(new ThreadStart(StartListen));
th.Start();
}
public void StartListen()
{
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
tcpServer = new TcpListener(localAddr, Int32.Parse(tbPort.Text));
tcpServer.Start();
while (true)
{
Thread t = new Thread(new ParameterizedThreadStart(NewClient));
tcpClient = tcpServer.AcceptTcpClient();
t.Start(tcpClient);
count++;
}
}
public void StopServer()
{
if (tcpServer != null)
{
tvClientList.Nodes[0].Nodes.Clear();
th.Abort();
tcpServer.Stop();
}
tbPort.Enabled = true;
}
public void NewClient(Object obj)
{
ClientAdded(this, new MyEventArgs((TcpClient)obj));
}
public void ClientAdded(object sender, EventArgs e)
{
tcpClient = ((MyEventArgs)e).clientSock;
String remoteIP = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString();
String remotePort = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Port.ToString();
UpdateClientList(remoteIP + " : " + remotePort, "Add");
connectedClient = tcpClient;
clientStream = tcpClient.GetStream();
StateObject state = new StateObject();
state.workSocket = connectedClient.Client;
connectedClient.Client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(OnReceive), state);
}
private void UpdateClientList(string str, string type)
{
if (this.tvClientList.InvokeRequired)
{
SetListBoxItem d = new SetListBoxItem(UpdateClientList);
this.Invoke(d, new object[] { str, type });
}
else
{
if (type.Equals("Add"))
{
this.tvClientList.Nodes[0].Nodes.Add(str);
}
else
{
foreach (TreeNode n in this.tvClientList.Nodes[0].Nodes)
{
if (n.Text.Equals(str))
this.tvClientList.Nodes.Remove(n);
}
}
}
}
private void tvClientList_DoubleClick(object sender, System.EventArgs e)
{
}
private void Form1_FormClosing(Object sender, FormClosingEventArgs e)
{
StopServer();
}
private void cbStartStop_CheckedChanged_1(object sender, EventArgs e)
{
if (cbStartStop.Checked == true)
{
try
{
int port;
port = Int32.Parse(tbPort.Text);
string cx = tbPort.Text.ToString();
StartServer();
MessageBox.Show("connect!!!" + cx);
}
catch (Exception ex)
{
MessageBox.Show("Please enter the correct port number!!!");
cbStartStop.Checked = false;
}
}
else
{
StopServer();
}
}
private void SetText(string text)
{
String remotePort = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Port.ToString();
if (this.rtbchattting.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.rtbchattting.SelectionColor = Color.Blue;
this.rtbchattting.SelectedText = remotePort +" : " + text +"\n";
}
}
public void OnReceive(IAsyncResult ar)
{
String content = String.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead;
if (handler.Connected)
{
try
{
bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Remove(0, state.sb.Length);
state.sb.Append(Encoding.ASCII.GetString(
state.buffer, 0, bytesRead));
content = state.sb.ToString();
SetText(content);
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(OnReceive), state);
}
}
catch (SocketException socketException)
{
if (socketException.ErrorCode == 10054 || ((socketException.ErrorCode != 10004) && (socketException.ErrorCode != 10053)))
{
String remoteIP = ((IPEndPoint)handler.RemoteEndPoint).Address.ToString();
String remotePort = ((IPEndPoint)handler.RemoteEndPoint).Port.ToString();
handler.Close();
handler = null;
}
}
catch (Exception exception)
{
MessageBox.Show(exception.Message + "\n" + exception.StackTrace);
}
}
}
public class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
private void Btn_Kirim_Click(object sender, EventArgs e)
{
byte[] chatts;
chatts = Encoding.ASCII.GetBytes(tbSendChat.Text);
if (String.IsNullOrEmpty(tbNoClient.Text))
{
MessageBox.Show("Enter Material Name Please.");
}
else{
connectedClient.Client.Send(chatts);
}
rtbchattting.SelectionColor = Color.IndianRed;
rtbchattting.SelectedText = "\nServer: " + tbSendChat.Text + "\n";
}
}
}
in MyEventArgs.cs
namespace serverchat
{
class MyEventArgs : EventArgs
{
private TcpClient sock;
public TcpClient clientSock
{
get { return sock; }
set { sock = value; }
}
public MyEventArgs(TcpClient tcpClient)
{
sock = tcpClient;
}
}
}