!!I know there is questions with the same exception message that have been answered. I have read them, and it is not much like my problem.
1.I am learning about a sockect TCP Window App for microsoft visual studio
2.For this project it is working as server side and client side
3.Initially, it works well when it is in the same project. And the client form is triggered each time user click the button on server from.
4.But when I tried separate server and client in different forms, the problem comes.
5.To make them separate completely, I deleted the button and its control. And it can start normally. The server form code I have is as following:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ChatApp.Forms;
using NetComm;
namespace ChatApp
{
public partial class Form1 : Form
{
private NetComm.Host server = new Host(3330); // Listens on port 3330.
private int activeConnections = 0;
private delegate void DisplayInformationDelegate(string s);
private ArrayList clientList = new ArrayList(); // Share amongst all instances of the Clients
public Form1()
{
InitializeComponent();
server.ConnectionClosed += Server_ConnectionClosed;
server.DataReceived += Server_DataReceived;
server.DataTransferred += Server_DataTransferred;
server.errEncounter += ServerErrEncounter;
server.lostConnection += ServerLostConnection;
server.onConnection += ServerOnConnection;
server.StartConnection();
rtbConOut.AppendText(Environment.NewLine);
}
void ServerOnConnection(string id)
{
activeConnections++;
lblConnections.Text = activeConnections.ToString();
DisplayInformation(String.Format("Client {0} Connected", id));
clientList.Add(id);
SendClientList();
}
private void SendClientList()
{
DisplayInformation("Sending All Clients a list of currently available clients"); // This is not how we would normally do this
foreach (string cid in clientList)
{
foreach (string cid2 in clientList)
{
byte[] d = ConvertStringToBytes("CList::" + cid);
server.SendData(cid2, d);
}
}
}
void ServerLostConnection(string id)
{
lblConnections.Text = activeConnections.ToString();
DisplayInformation(String.Format("Client {0} Lost Connection", id));
clientList.Remove(id);
}
void ServerErrEncounter(Exception ex)
{
DisplayInformation("Server Error " + ex.Message);
}
void Server_DataTransferred(string sender, string recipient, byte[] data)
{
string senderId = (string)sender;
if (recipient == "0")
{
DisplayInformation("Received Command From Client " + senderId + " for this Server");
switch (ConvertBytesToString(data))
{
case "CLOSING":
activeConnections--;
lblConnections.Text = activeConnections.ToString();
DisplayInformation("Client " + senderId + " is Closing");
clientList.Remove(senderId);
SendClientList();
break;
default:
foreach (string id in clientList)
{
if (id != senderId) // Don't send this message to the client that sent the message in the first place
{
server.SendData(id, data);
}
}
break;
}
}
else
{
DisplayInformation("Received Command From Client " + senderId + " for Client " + recipient);
}
}
void Server_DataReceived(string iD, byte[] data)
{
if (ConvertBytesToString(data) == "CLOSING")
{
DisplayInformation("Client " + iD + " has closed");
}
}
void Server_ConnectionClosed()
{
DisplayInformation("Connection Was Closed");
}
string ConvertBytesToString(byte[] bytes)
{
return ASCIIEncoding.ASCII.GetString(bytes);
}
byte[] ConvertStringToBytes(string str)
{
return ASCIIEncoding.ASCII.GetBytes(str);
}
void DisplayInformation(string s)
{
if (this.rtbConOut.InvokeRequired)
{
DisplayInformationDelegate d = new DisplayInformationDelegate(DisplayInformation);
this.rtbConOut.Invoke(d, new object[] { s });
}
else
{
this.rtbConOut.AppendText(s + Environment.NewLine);
}
}
}
}
So as client side, the code is as follows:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using NetComm;
namespace ChatApp.Forms
{
public partial class FrmClient : Form
{
public string Name { get; set; }
public string MyKey { get; set; }
private string prefix;
private NetComm.Client client = new Client();
private ArrayList clientList = new ArrayList();
public FrmClient()
{
InitializeComponent();
CreateMyForm(this);
}
private void FrmClient_Load(object sender, EventArgs e)
{
client.Connected += ClientConnected;
client.DataReceived += ClientDataReceived;
client.Disconnected += ClientDisconnected;
client.errEncounter += ClientErrEncounter;
client.Connect("127.0.0.1", 3330, Name);
prefix = Name + "(" + MyKey + ")";
this.Text = prefix;
}
void ClientErrEncounter(Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
void ClientDisconnected()
{
MessageBox.Show("You have been Disconnected");
}
void ClientDataReceived(byte[] data, string iD)
{
//CList::
string msg = ConvertBytesToString(data);
if (msg.StartsWith("CList::"))
{
string msgs = msg.Replace("CList::","");
rtbConOut.AppendText("Clients online Now are " + msgs + Environment.NewLine);
}
else
{
rtbConOut.AppendText(msg + Environment.NewLine);
}
}
void ClientConnected()
{
rtbConOut.AppendText("Connected " + Environment.NewLine);
}
string ConvertBytesToString(byte[] bytes)
{
return ASCIIEncoding.ASCII.GetString(bytes);
}
byte[] ConvertStringToBytes(string str)
{
return ASCIIEncoding.ASCII.GetBytes(str);
}
private void FrmClient_FormClosing(object sender, FormClosingEventArgs e)
{
client.SendData(ConvertStringToBytes("CLOSING"), "0");
client.Disconnect();
}
public void CreateMyForm(FrmClient client)
{
// Create a new instance of the form.
Form form1 = new Form();
// Create two buttons to use as the accept and cancel buttons.
Button button1 = new Button();
Button button2 = new Button();
TextBox name = new TextBox();
TextBox mykey = new TextBox();
Label nlabel = new Label();
Label klabel = new Label();
nlabel.Text = "Chat Name: ";
klabel.Text = "Public Key: ";
// Set the text of button1 to "OK".
button1.Text = "OK";
// Set the position of the button on the form.
button1.Location = new Point(80, 120);
// Set the text of button2 to "Cancel".
button2.Text = "Cancel";
// Set the position of the button based on the location of button1.
button2.Location = new Point(button1.Left + button1.Width, 120);
// Make button1's dialog result OK.
button1.DialogResult = DialogResult.OK;
// Make button2's dialog result Cancel.
button2.DialogResult = DialogResult.Cancel;
nlabel.Location = new Point(20, 60);
nlabel.Width = 80;
klabel.Location = new Point(20, nlabel.Top + nlabel.Height + 15);
klabel.Width = 80;
name.Width = 150;
mykey.Width = 150;
name.Location = new Point(100, 60);
mykey.Location = new Point(name.Left, name.Top + name.Height + 15);
// Set the caption bar text of the form.
form1.Text = "Create new Client";
form1.Controls.Add(name);
form1.Controls.Add(mykey);
form1.Controls.Add(nlabel);
form1.Controls.Add(klabel);
// Define the border style of the form to a dialog box.
form1.FormBorderStyle = FormBorderStyle.FixedDialog;
// Set the accept button of the form to button1.
form1.AcceptButton = button1;
// Set the cancel button of the form to button2.
form1.CancelButton = button2;
// Set the start position of the form to the center of the screen.
form1.StartPosition = FormStartPosition.CenterScreen;
// Add button1 to the form.
form1.Controls.Add(button1);
// Add button2 to the form.
form1.Controls.Add(button2);
// Display the form as a modal dialog box.
form1.ShowDialog();
// Determine if the OK button was clicked on the dialog box.
if (form1.DialogResult == DialogResult.OK)
{
if (name.Text != "" && mykey.Text != "")
{
client.Name = name.Text;
client.MyKey = mykey.Text;
form1.Dispose();
client.Show();
}
else
{
MessageBox.Show("Please fill the from before click OK!");
}
}
else
{
form1.Dispose();
}
}
private void TbInputKeyUp(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter || e.KeyData == Keys.Return) // If the user has pressed the enter key
{
if (tbInput.Text.Length > 0) // If there is something to send
{
client.SendData(ConvertStringToBytes(tbInput.Text), "0");
rtbConOut.AppendText(tbInput.Text + Environment.NewLine);
tbInput.Text = "";
}
}
}
private void BtnSendClick(object sender, EventArgs e)
{
if (tbInput.Text.Length > 0) // If there is something to send
{
client.SendData(ConvertStringToBytes(tbInput.Text), "0");
rtbConOut.AppendText(tbInput.Text + Environment.NewLine);
tbInput.Text = "";
}
}
}
}