using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace Server
{
//The commands for interaction between the server and the client
enum Command
{
Login, //Log into the server
Logout, //Logout of the server
Message, //Send a text message to all the chat clients
List, //Get a list of users in the chat room from the server
Null //No command
}
public partial class SGSserverForm : Form
{
//The main socket on which the server listens to the clients
Socket serverSocket;
public EndPoint epSender;
public string strName = "Raj";
byte[] byteData = new byte[1024];
public SGSserverForm()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
CheckForIllegalCrossThreadCalls = false;
//We are using UDP sockets
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 1000);
//Bind this address to the server
serverSocket.Bind(ipeSender);
//The epSender identifies the incoming clients
EndPoint epSender = (EndPoint)ipeSender;
//Start receiving data
serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SGSServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void OnReceive(IAsyncResult ar)
{
try
{
IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 1000);
EndPoint epSender = (EndPoint)ipeSender;
serverSocket.EndReceiveFrom(ar, ref epSender);
Data msgReceived = new Data(byteData);
//We will send this object in response the users request
Data msgToSend = new Data();
byte[] message;
msgToSend.cmdCommand = msgReceived.cmdCommand;
msgToSend.strName = msgReceived.strName;
msgToSend.strMessage = msgReceived.strName + ":" + msgReceived.strMessage;
message = msgToSend.ToByte();
serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, epSender, new AsyncCallback(OnSend), epSender);
txtLog.Text += msgToSend.strMessage + "\r\n";
serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SGSServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void OnSend(IAsyncResult ar)
{
try
{
serverSocket.EndSend(ar);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SGSServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
//Fill the info for the message to be send
Data msgToSend = new Data();
// msgToSend.strName = strName;
msgToSend.strMessage = textBox1.Text;
msgToSend.cmdCommand = Command.Message;
byte[] byteData = msgToSend.ToByte();
//Send it to the server
serverSocket.BeginSendTo(byteData, 0, byteData.Length, SocketFlags.None, epSender, new AsyncCallback(OnSend), null);
//txtMessage.Text = null;
}
catch (Exception)
{
MessageBox.Show("Unable to send message to the server.", "SGSclientUDP: ", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void textBox1_Enter(object sender, EventArgs e)
{ }
}
//The data structure by which the server and the client interact with
//each other
class Data
{
//Default constructor
public Data()
{
this.cmdCommand = Command.Null;
this.strMessage = null;
this.strName = null;
}
//Converts the bytes into an object of type Data
public Data(byte[] data)
{
//The first four bytes are for the Command
this.cmdCommand = (Command)BitConverter.ToInt32(data, 0);
//The next four store the length of the name
int nameLen = BitConverter.ToInt32(data, 4);
//The next four store the length of the message
int msgLen = BitConverter.ToInt32(data, 8);
//This check makes sure that strName has been passed in the array of bytes
if (nameLen > 0)
this.strName = Encoding.UTF8.GetString(data, 12, nameLen);
else
this.strName = null;
//This checks for a null message field
if (msgLen > 0)
this.strMessage = Encoding.UTF8.GetString(data, 12 + nameLen, msgLen);
else
this.strMessage = null;
}
//Converts the Data structure into an array of bytes
public byte[] ToByte()
{
List<byte> result = new List<byte>();
//First four are for the Command
result.AddRange(BitConverter.GetBytes((int)cmdCommand));
//Add the length of the name
if (strName != null)
result.AddRange(BitConverter.GetBytes(strName.Length));
else
result.AddRange(BitConverter.GetBytes(0));
//Length of the message
if (strMessage != null)
result.AddRange(BitConverter.GetBytes(strMessage.Length));
else
result.AddRange(BitConverter.GetBytes(0));
//Add the name
if (strName != null)
result.AddRange(Encoding.UTF8.GetBytes(strName));
//And, lastly we add the message text to our array of bytes
if (strMessage != null)
result.AddRange(Encoding.UTF8.GetBytes(strMessage));
return result.ToArray();
}
public string strName; //Name by which the client logs into the room
public string strMessage; //Message text
public Command cmdCommand; //Command type (login, logout, send message, etcetera)
}
}
And this is my client code :
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace SGSclient
{
//The commands for interaction between the server and th
enum Command
{
Login, //Log into the server
Logout, //Logout of the server
Message, //Send a text message to all the chat clients
List, //Get a list of users in the chat room from the server
Null //No command
}
public partial class SGSClient : Form
{
public Socket clientSocket; //The main client socket
public string strName = "Naveen"; //Name by which the user logs into the room
public EndPoint epServer; //The EndPoint of the server
byte[] byteData = new byte[1024];
public SGSClient()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //IP address of the server machine
IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); //Server is listening on port 1000
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1000);
epServer = (EndPoint)ipEndPoint;
this.Text = "SGSclient: " + strName;
//The user has logged into the system so we now request the server to send
Data msgToSend = new Data();
msgToSend.cmdCommand = Command.List;
msgToSend.strName = strName;
msgToSend.strMessage = null;
byteData = msgToSend.ToByte();
clientSocket.BeginSendTo(byteData, 0, byteData.Length, SocketFlags.None, epServer,
new AsyncCallback(OnSend), null);
byteData = new byte[1024];
//Start listening to the data asynchronously
clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epServer, new AsyncCallback(OnReceive), null);
}
private void OnSend(IAsyncResult ar)
{
try
{
clientSocket.EndSend(ar);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SGSclient: " + strName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void OnReceive(IAsyncResult ar)
{
try
{
clientSocket.EndReceive(ar);
//Convert the bytes received into an object of type Data
Data msgReceived = new Data(byteData);
string data = Encoding.UTF8.GetString(byteData);
txtChatBox.Text += data.ToString() + "\r\n";
//Accordingly process the message received
switch (msgReceived.cmdCommand)
{
case Command.Message:
break;
case Command.List:
txtChatBox.Text += "<<<" + strName + " has joined the room>>>\r\n";
break;
}
if (msgReceived.strMessage != null)
txtChatBox.Text += msgReceived.strMessage + "\r\n";
byteData = new byte[1024];
//Start listening to receive more data from the user
clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epServer, new AsyncCallback(OnReceive), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "SGSclient: " + strName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void txtMessage_TextChanged(object sender, EventArgs e)
{
try
{
//Fill the info for the message to be send
Data msgToSend = new Data();
msgToSend.strName = strName;
msgToSend.strMessage = txtMessage.Text;
msgToSend.cmdCommand = Command.Message;
byte[] byteData = msgToSend.ToByte();
byte[] bytes = Encoding.ASCII.GetBytes(txtMessage.Text);
//Send it to the server
clientSocket.BeginSendTo(byteData, 0, byteData.Length, SocketFlags.None, epServer, new AsyncCallback(OnSend), null);
}
catch (Exception)
{
MessageBox.Show("Unable to send message to the server.", "SGSclientUDP: " + strName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
//The data structure by which the server and the client interact.
class Data
{
//Default constructor
public Data()
{
this.strMessage = null;
this.strName = null;
}
//Converts the bytes into an object of type Data
public Data(byte[] data)
{
//The first four bytes are for the Command
this.cmdCommand = (Command)BitConverter.ToInt32(data, 0);
//The next four store the length of the name
int nameLen = BitConverter.ToInt32(data, 4);
//The next four store the length of the message
int msgLen = BitConverter.ToInt32(data, 8);
//This check makes sure that strName has been passed in the array of bytes
if (nameLen > 0)
this.strName = Encoding.UTF8.GetString(data, 12, nameLen);
else
this.strName = null;
//This checks for a null message field
if (msgLen > 0)
this.strMessage = Encoding.UTF8.GetString(data, 12 + nameLen, msgLen);
else
this.strMessage = null;
}
//Converts the Data structure into an array of bytes
public byte[] ToByte()
{
List<byte> result = new List<byte>();
//First four are for the Command
result.AddRange(BitConverter.GetBytes((int)cmdCommand));
//Add the length of the name
if (strName != null)
result.AddRange(BitConverter.GetBytes(strName.Length));
else
result.AddRange(BitConverter.GetBytes(0));
//Length of the message
if (strMessage != null)
result.AddRange(BitConverter.GetBytes(strMessage.Length));
else
result.AddRange(BitConverter.GetBytes(0));
//Add the name
if (strName != null)
result.AddRange(Encoding.UTF8.GetBytes(strName));
//And, lastly we add the message text to our array of bytes
if (strMessage != null)
result.AddRange(Encoding.UTF8.GetBytes(strMessage));
return result.ToArray();
}
public string strName; //Name by which the client logs into the room
public string strMessage; //Message text
public Command cmdCommand; //Command type (login, logout, send message, etcetera)
}
}
Now i am able to send data from client to server but when i want to send data from server to client it is catching exception.why??
Thanks!