c#


C# server and client communication - send/receive data


I need to help, I want to make server and client, who will communicate together.(send/receive data)
Example: client sends username and password to server when I login and server checks it and sends (correct or not correct) to client.
Server and client can send and receive data, and more data together (for example: username, password ... in one communication)
I need from you the best example of communicating with the client, server, currently I have this script by youtube: enter link description here
There is send / receive method from youtube:
public class PacketWriter : BinaryWriter
{
// This will hold our packet bytes.
private MemoryStream _ms;
// We will use this to serialize (Not in this tutorial)
private BinaryFormatter _bf;
public PacketWriter() : base()
{
// Initialize our variables
_ms = new MemoryStream();
_bf = new BinaryFormatter();
// Set the stream of the underlying BinaryWriter to our memory stream.
OutStream = _ms;
}
public void Write(Image image)
{
var ms = new MemoryStream(); //Create a memory stream to store our image bytes.
image.Save(ms, ImageFormat.Png); //Save the image to the stream.
ms.Close(); //Close the stream.
byte[] imageBytes = ms.ToArray(); //Grab the bytes from the stream.
//Write the image bytes to our memory stream
//Length then bytes
Write(imageBytes.Length);
Write(imageBytes);
}
public void WriteT(object obj)
{
//We use the BinaryFormatter to serialize our object to the stream.
_bf.Serialize(_ms, obj);
}
public byte[] GetBytes()
{
Close(); //Close the Stream. We no longer have need for it.
byte[] data = _ms.ToArray(); //Grab the bytes and return.
return data;
}
}
public class PacketReader : BinaryReader
{
// This will be used for deserializing
private BinaryFormatter _bf;
public PacketReader(byte[] data) : base(new MemoryStream(data))
{
_bf = new BinaryFormatter();
}
public Image ReadImage()
{
//Read the length first as we wrote it.
int len = ReadInt32();
//Read the bytes
byte[] bytes = ReadBytes(len);
Image img; //This will hold the image.
using (MemoryStream ms = new MemoryStream(bytes))
{
img = Image.FromStream(ms); //Get the image from the stream of the bytes.
}
return img; //Return the image.
}
public T ReadObject<T>()
{
//Use the BinaryFormatter to deserialize the object and return it casted as T
/* MSDN Generics
* http://msdn.microsoft.com/en-us/library/ms379564%28v=vs.80%29.aspx
*/
return (T)_bf.Deserialize(BaseStream);
}
}
I don't know if it is better method, I don't have experience with it, so I want to ask someone more experienced.
Is good method make images from data and send?
Thank you for any advice, I will be grateful!
Check out this CodeProject example, it seems to be what you're looking for. You'll need two separate applications, one for your server and the other for your client.
Server: Essentially all you need to do here is open up a TcpListener and receive the bytes from it. From the CodeProject article:
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
public class serv {
public static void Main() {
try {
IPAddress ipAd = IPAddress.Parse("172.21.5.99");
// use local m/c IP address, and
// use the same in the client
/* Initializes the Listener */
TcpListener myList=new TcpListener(ipAd,8001);
/* Start Listening at the specified port */
myList.Start();
Console.WriteLine("The server is running at port 8001...");
Console.WriteLine("The local End point is :" +
myList.LocalEndpoint );
Console.WriteLine("Waiting for a connection.....");
Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] 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]));
ASCIIEncoding asen=new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
s.Close();
myList.Stop();
}
catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
Client: The client is pretty similar, except instead of using a TcpListener, you'd use a TcpClient. Again from CodeProject:
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
public class clnt {
public static void Main() {
try {
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("172.21.5.99",8001);
// use the ipaddress as in the server program
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
String str=Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen= new ASCIIEncoding();
byte[] ba=asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba,0,ba.Length);
byte[] bb=new byte[100];
int k=stm.Read(bb,0,100);
for (int i=0;i<k;i++)
Console.Write(Convert.ToChar(bb[i]));
tcpclnt.Close();
}
catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
This is a very basic example of how you can do some simple networking tasks in .Net; if you're planning on creating web-based applications I'd recommend you use WCF/Asp.Net.

Related Links

Is there a way to initialize properties after construction of object?
Assignment Expression in VB.Net
log4net mapping custom data to field in database
Considerations for not awaiting a Task in an asynchronous method
Azure Mobile Services Custom LoginProvider redirect issues in Universal App with AuthenticationHandler
Converting 2D array to string in C#
How to return unparsed string instead of DateTime from JProperty [duplicate]
how to access a child element dynamically in WPF
How to use Google Play Leaderboards in Xamarin / Monogame
How to work with the contents of my array?
How does autofac determine lifetime scope on injected parameters
How can i change in Graphics DrawString the text font size?
Default value for DateTime in DevForce 2012
Refactor many HasColumnAnnotation and IndexAnnotation usages in my schema definition
Waiting on tasks in ASP.NET WebPages Razor view
how to resize columns in datagridview in C#

Categories

HOME
packet
liquibase
glsl
x509certificate
artifactory
ms-access-2010
open-search-server
rename
google-app-maker
urllib2
distinct
mbed
eclipse-orion
webseal
jquery-easyui
spring-webflow
typedef
smali
tcpdf
functional-dependencies
policy
ballerinalang
spock
pushpad
hierarchy
lines
wit-ai
certbot
cocoa-scripting
aweber
sdl-2
motherboard
android-databinding
kdevelop
motion
ssdp
android-graphview
ape-phylo
gridgain
text-formatting
easyquery
hellosign
liferay-ide
petapoco
timex
mavlink
git-cherry-pick
supervised-learning
transaction-isolation
aws-kms
3d-rendering
boost-propertytree
std
askbot
jquery-draggable
wonderware
web-performance
app-data
play-json
traminer
musicbrainz
transparentproxy
log-analysis
opennebula
tidesdk
jeet-grid
pymol
chrome-mobile
kss
information-hiding
disabled-control
visual-studio-setup-proje
satisfiability
slimscroll
node-amqp
angularjs-select2
azure-pack
pymel
string-length
idoc
correctness
php-gettext
systrace
bindinglist
eeprom
advanceddatagrid
sessiontracking
jqtransform
database-agnostic
unauthorized
scalable

Resources

Encrypt Message