Simple C # Socket programming

Source: Internet
Author: User
Tags socket

servers, server code.

Connect using socket sockets.

1 using System;
2 using System.Net;
3 using System.Net.Sockets;
4 using System.IO;
5
6 Publi C Class Echoserver
7 {
8//entry Point of the main method.
9 public static void main ()
{
One//tcp Listener is listening on the given port
Int32 port = 1234;
\
//ipaddress is CONNETCT IP address//ipaddress addr = Ipaddress.parse ("127.0.0.1");
IPAddress ipaddress = dns.resolve ("localhost"). ADDRESSLIST[0];

TcpListener tcplistener = new TcpListener (ipaddress,port);
Tcplistener.start ()
Cons Ole. WriteLine ("Server started");
//accepts A new connection
Socket socketforclient = Tcplistener.acceptsocket ();
//streamwri ter and StreamReader Classes for reading and writing the "Data to and" from.
//the server reads the meassage sent by the Client, converts it to upper case and sends it back to the client.< br>//lastly Close all thE streams.        
Try
{
socketforclient.connected)
{
while (true)
31 {
Console.WriteLine ("Client Connected");
NetworkStream NetworkStream = new NetworkStream (socketforclient);
StreamWriter streamwriter = new StreamWriter (NetworkStream);
StreamReader StreamReader = new StreamReader (NetworkStream);
String line = StreamReader.ReadLine ();
Notoginseng Console.WriteLine ("Read:" +line);
Line=line. ToUpper () + "!";
Streamwriter.writeline (line);
Console.WriteLine ("wrote:" +line);
StreamWriter.Flush ();
42}
43}
Socketforclient.close ();
Console.WriteLine ("Exiting");
46}
catch (Exception e)
, {
Console.WriteLine (e.tostring ());
}
I}
'

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.