I'm looking to implement a simple Client/Server setup that can transfer a serialized EmailRequest
object (using XmlSerializer
) from the client to the server, to be used to send an email.
Server
class Program
{
private static void Main()
{
try
{
TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8888);
listener.Start();
while (true)
{
Console.WriteLine("Waiting for request..");
TcpClient client = listener.AcceptTcpClient();
NetworkStream stream = client.GetStream();
XmlSerializer serializer = new XmlSerializer(typeof(EmailRequest));
EmailRequest request = (EmailRequest)serializer.Deserialize(stream); // This is where the problem is //
bool success = SendGridUtility.SendEmail(request.Recipients, request.Subject,
request.BodyType == EmailRequest.Type.Plain ? request.PlainText : request.HTMLText,
request.BodyType).Result;
byte[] response = Encoding.ASCII.GetBytes(success ? "Success" : "Failure");
Console.WriteLine("Email Successfully Sent!");
stream.Write(response, 0, response.Length);
}
}
catch (Exception e)
{
Console.WriteLine("Something went wrong.. :( :\n" + e.Message + "\n\n");
}
Console.ReadLine();
}
}
Client
class Program
{
static void Main(string[] args)
{
try
{
TcpClient client = new TcpClient("127.0.0.1", 8888);
NetworkStream stream = client.GetStream();
XmlSerializer serializer = new XmlSerializer(typeof(EmailRequest));
EmailRequest request = new EmailRequest
{
BodyType = EmailRequest.Type.Plain,
HTMLText = "not used",
PlainText = "Email Body",
Recipients = new List<string> {"johnsmith@example.com"},
Subject = "Email Subject"
};
serializer.Serialize(stream,request);
Byte[] data = new Byte[256];
Int32 bytes = stream.Read(data, 0, data.Length);
string responseData = Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace + "\n\n");
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
}
EmailRequest Model
[Serializable]
public class EmailRequest
{
public enum Type
{
Plain,
HTML
}
public List<string> Recipients { get; set; }
public string Subject { get; set; }
public Type BodyType { get; set; }
public string PlainText { get; set; }
public string HTMLText { get; set; }
}
When the program reaches the Deserialize
method, the application doesn't hang, but waits, as though it's expecting user-input, and I have no idea why. I've got no experience with TCP/XmlSerialization/Streams apart from what I've done today. Any help or suggestions as to how I could improve the program would, as always, be much appreciated. Thanks.