Definition: A socket is one end of a two-way communications link between two programs running on the network
One end to the Machine will be server & others connecting to the machine are clients.client program can write requests to the socket, and the server will process your request and return the results back to you via the socket. Sockets are low-level connections. The client and the server both communicate through a stream of bytes written to the socket. The client and the server must agree on a protocol--that is, they must agree on the language of the information transferred back and forth through the socket.
Simple Socket connection between Server and Clinet
Server Side:
* Create a Socket Instance
* Bind the Socket and make to Listen
* Call a thread to receive data from client and call Accept function
using System.Net; using System.Net.Sockets; using System.Threading;
public partial class Serverconnect : System.Web.UI.Page { Socket skt; Thread th; IPEndPoint ipend;
protected void Page_Load(object sender, EventArgs e) { skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ipend = new IPEndPoint(IPAddress.Any, 5000); skt.Bind(ipend); skt.Listen(-1); th=new Thread(new ThreadStart(Rec)); th.Start();
}
void Rec() { while (true) { new_sckt = skt.Accept();
byte[] buff = new byte[1024];
EndPoint ip = (EndPoint)ipend; new_sckt.Receive(buff);
string s = Encoding.ASCII.GetString(buff); Response.Write(s); } }
First while writting the socket program u need to create a server socket to bind all the clients.
Client side connection:
* Create a Socket Connection(Give AddressFamily,SocketType,ProtocolType)
* Call IpEndpoint giving the perticular server Ipaddress
* Call Socket.Connect to connect with server
using System.Net; using System.Net.Sockets; using System.Threading;
public partial class Serverconnect : System.Web.UI.Page { Socket client_skt; Thread th; IPEndPoint ipend;
protected void Page_Load(object sender, EventArgs e) { client_skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipend = new IPEndPoint(IPAddress.Parse("192.168.50.90"), 5000);
client_skt.Connect(ipend); byte[] buff = Encoding.ASCII.GetBytes(textBox1.Text);
client_skt.Send(buff); }
void Rec() { while (true) { new_sckt = client_skt.Accept();
byte[] buff = new byte[1024];
EndPoint ip = (EndPoint)ipend; new_sckt.Receive(buff);
string s = Encoding.ASCII.GetString(buff); Response.Write(s); } }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|