Ciwan

Ciwan

  • NA
  • 9
  • 19.1k

Slightly Harder Socket Programming

Feb 6 2011 10:10 AM


Hello Friends.

I have a Product class, and it is programmed to act as a data structure basically. Here is the code:

 
using System;
namespace
OOSys
{
class Product
{
private int ProductNo { get; set; }
private string ProductName { get; set; }
private string ProductType { get; set; }
private double ProductPrice { get; set; }
private string ProductMaker { get; set; }
// Constructor
public Product(int number, string name, string type, double price, string maker)
{
ProductNo = number;
ProductName = name;
ProductType = type;
ProductPrice = price;
ProductMaker = maker;
}
}
}


What I want to do is serialize a product, and send it via socket to another running program. I've called my two programs Client and Server. Here is the code for my Client class:

 
using System;
using
System.Net;
using
System.Net.Sockets;
namespace
OOSys
{
class Client
{
static void Main(string[] args)
{
try
{
Product p = new Product(1, "CoD", "Shooter", 39.99, "UbiSoft");
string userInputString;
Console.WriteLine("This program will transfer a product to a server. \n");
Console.WriteLine("Please type the number 1 followed by Enter to send the Product:");
userInputString =
Console.ReadLine();
if (userInputString == "1")
{
Console.WriteLine("You Entered: " + userInputString);
Console.WriteLine("Status: Sending Product ... ...");
IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
IPEndPoint remoteEP = new IPEndPoint(ipAddress[0], 8221);
Socket socClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
socClient.Bind(remoteEP);
socClient.Connect(remoteEP);

byte[] ProductData = System.Text.Encoding.ASCII.GetBytes(userInputString);
socClient.Send(ProductData);
socClient.Close();
Console.ReadLine();
}
else
{
Console.WriteLine("Nothing will be sent !");
}

}
catch (SocketException se)
{
Console.WriteLine(se);
}
}
}
}


 
Ignoring the Server side program for now (I'll move onto that in a bit) ... do you see anything wrong with the above code ?

I have read the articles on the right, but they were just general info, I couldn't see anything about sending Objects to a Server program.

I would greatly appreciate any help with this.

Thank you.

Answers (2)