I am working on a server / client project. The client will request information from the server, and the server will send them back to the client.
The information may be a string, number, array, list, arraylist, or any other object. The solution I have found so far is to serialize the object (data) and send it, and then de-serialize it for processing.
Here is the server code:
public void RunServer(string SrvIP,int SrvPort)
{
try
{
var ipAd = IPAddress.Parse(SrvIP);
if (ipAd != null)
{
var myList = new TcpListener(ipAd, SrvPort);
myList.Start();
Console.WriteLine("The server is running at port "+SrvPort+"...");
Console.WriteLine("The local End point is :" + myList.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
while (true)
{
Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
var b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("Recieved...");
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
string cmd = Encoding.ASCII.GetString(b);
if (cmd.Contains("CLOSE-CONNECTION"))
break;
var asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was received by the server."));
Console.WriteLine("\nSent Acknowledgement");
s.Close();
Console.ReadLine();
}
myList.Stop();
}
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
here is the client code that should return an object
public object runClient(string SrvIP, int SrvPort)
{
object obj = null;
try
{
var tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect(SrvIP, SrvPort);
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
var str = Console.ReadLine();
Stream stm = tcpclnt.GetStream();
var asen = new ASCIIEncoding();
if (str != null)
{
var ba = asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba, 0, ba.Length);
}
var bb = new byte[2000];
var k = stm.Read(bb, 0, bb.Length);
string data = null;
for (var i = 0; i < k; i++)
Console.Write(Convert.ToChar(bb[i]));
Console.ReadLine();
tcpclnt.Close();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
return obj;
}
I need to know a good serialize / serialize and how to integrate it into the solution above.
source
share