ZengCode.Com (The Thai Php Framework)  


Home   Download   Manual   About us    

Facebook   


MAIN MENU
เขียนโปรแกรมบน iPhone ด้วย MonoTouch
News
Php Tips
Ubuntu
Spring+Strut+Hibernate
Android Programming
Design Pattern By PHP
C# Design Pattern
Linux Quick Tips
C# Tips & Technique
C# using Linq น่าใช้จริงๆ
Java & JavaScript Tips
MAVEN
Database & SQL
ZengCode Framework Guide
Mac OSx
Zeng Code Code
Programming
IPhone (Tips and Trick)

Download เอกสารที่น่าสนใจ

     ฺBasic TCP/IP Socket in C#  (2009-09-11)

Server

using System;
using System.Threading;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Configuration;

class EmployeeTCPServer
{
    static TcpListener listener;

    public static void Main()
    {
        System.Net.IPAddress localaddr = System.Net.IPAddress.Parse("127.0.0.1");
        listener = new TcpListener(localaddr, 2055);
        listener.Start();

            Console.WriteLine("Server mounted, listening to port 2055");


        while (true)
        {
            Socket soc = listener.AcceptSocket();

                Console.WriteLine("Connected: {0}", soc.RemoteEndPoint);

            try
            {
                Stream s = new NetworkStream(soc);
                StreamReader sr = new StreamReader(s);
                StreamWriter sw = new StreamWriter(s);
                sw.AutoFlush = true; // enable automatic flushing

                while (true)
                {
                    string name = sr.ReadLine();
                    if (name == "" || name == null) break;
                    string job = name;
                    if (job == null) job = "No such employee";
                    Console.WriteLine("Recieve => "+job);
                    sw.WriteLine("You send me ==> "+job);
                }
                s.Close();
            }
            catch (Exception e)
            {

                    Console.WriteLine(e.Message);

            }

            soc.Close();
        }
    }
}

 

Client

using System;
using System.IO;
using System.Net.Sockets;

class EmployeeTCPClient
{
    public static void Main()
    {
        TcpClient client; // = new TcpClient("10.164.195.162", 2055);
        try
        {
            client = new TcpClient("127.0.0.1", 2055);
            Stream s = client.GetStream();
            StreamReader sr = new StreamReader(s);
            StreamWriter sw = new StreamWriter(s);
            sw.AutoFlush = true;
            Console.WriteLine("a");
            //Console.WriteLine(sr.ReadLine());
            Console.WriteLine("b");
            while (true)
            {
                Console.Write("Name: ");
                string name = Console.ReadLine();
                sw.WriteLine(name);
                if (name == "") break;
                Console.WriteLine(sr.ReadLine());
            }
            s.Close();
        }catch(Exception exp)
        {
            Console.WriteLine("Error : " + exp);
        }

        Console.Read();
    }
}


Comment

PEE  (11 กันยายน 2552)   
IP : 210.4.138.41
using System;
using System.Threading;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Configuration;

class EmployeeTCPServer{
    static TcpListener listener;
    const int LIMIT = 5; //5 concurrent clients
public static void Main(){ listener = new TcpListener(2055); listener.Start(); #if LOG Console.WriteLine("Server mounted,
listening to port 2055"
); #endif for(int i = 0;i < LIMIT;i++){ Thread t = new Thread(new ThreadStart(Service)); t.Start(); } } public static void Service(){ while(true){ Socket soc = listener.AcceptSocket(); //soc.SetSocketOption(SocketOptionLevel.Socket,
// SocketOptionName.ReceiveTimeout,10000);
#if LOG Console.WriteLine("Connected: {0}", soc.RemoteEndPoint); #endif try{ Stream s = new NetworkStream(soc); StreamReader sr = new StreamReader(s); StreamWriter sw = new StreamWriter(s); sw.AutoFlush = true; // enable automatic flushing
sw.WriteLine("{0} Employees available", ConfigurationSettings.AppSettings.Count); while(true){ string name = sr.ReadLine(); if(name == "" || name == null) break; string job = ConfigurationSettings.AppSettings[name]; if(job == null) job = "No such employee"; sw.WriteLine(job); } s.Close(); }catch(Exception e){ #if LOG Console.WriteLine(e.Message); #endif } #if LOG Console.WriteLine("Disconnected: {0}", soc.RemoteEndPoint); #endif soc.Close(); } } }


pee  (11 กันยายน 2552)   
IP : 210.4.138.41

using System;
using System.Threading;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Configuration;

class EmployeeTCPServer
{
    static TcpListener listener;
    const int LIMIT = 5; //5 concurrent clients


    public static void Main()
    {
        System.Net.IPAddress localaddr = System.Net.IPAddress.Parse("127.0.0.1");
        listener = new TcpListener(localaddr, 2055);
        listener.Start();

            Console.WriteLine("Server mounted, listening to port 2055");

        while (true)
        {
            Socket soc = listener.AcceptSocket();
            //Create Threading Here
                Console.WriteLine("Connected: {0}", soc.RemoteEndPoint);
        }
        /*
        while (true)
        {
            Socket soc = listener.AcceptSocket();

                Console.WriteLine("Connected: {0}", soc.RemoteEndPoint);

            try
            {
                Stream s = new NetworkStream(soc);
                StreamReader sr = new StreamReader(s);
                StreamWriter sw = new StreamWriter(s);
                sw.AutoFlush = true; // enable automatic flushing

               // sw.WriteLine("{0} Employees available",ConfigurationSettings.AppSettings.Count);
                while (true)
                {
                    string name = sr.ReadLine();
                    if (name == "" || name == null) break;
                    string job = name;
                    if (job == null) job = "No such employee";
                    Console.WriteLine("Recieve => "+job);
                    sw.WriteLine("You send me ==> "+job);
                }
                s.Close();
            }
            catch (Exception e)
            {

                    Console.WriteLine(e.Message);

            }

            soc.Close();
        }*/
    }
}



Pee  (11 กันยายน 2552)   
IP : 210.4.138.41

Introduction

This is a simple implementation of a TCP client server relationship.

To use

Compile the server and client programs separately. Before compiling change the IP address in both programs to match that of your machine (NOTE : to get your IP address  run 'ipconfig' from the command prompt in Windows NT/2000 m/c's)

When the server program is run, it will indicate at which IP it is running and the port it is listening to. Now run the client program is run , so as to establish a connection with the server.

When a connection is established the server will display the IP address and Port from where it has accepted the connection and client will ask for the string which is to be transmitted to the server.

The server on reciept of the string will display it, send an acknowledgement which will be recieved by the client.

The client can be either run from the same machine as the server or from a different machine. If run from a different machine then a network connection should exist between the machines running the server and client programs 

Collapse
//
/* Server Program */ 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 Listeneting 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"); /* clean up */ s.Close(); myList.Stop(); } catch (Exception e) { Console.WriteLine("Error..... " + e.StackTrace); } } } --------------------------------------------------------------------------- /* Client Program */ 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); } } } //

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

S.Thangaraju


Name
Comment
Security CodeCAPTCHA Image

web hit counter

This page took 0.048079 seconds to load.