SlideShare uma empresa Scribd logo
1 de 7
Lớp serverProgram
using   System;
using   System.Net;
using   System.Net.Sockets;
using   System.Collections.Generic;
using   System.Linq;
using   System.Text;

namespace server
{
    class ServerProgram
    {
        private IPAddress serverIP;
        public IPAddress ServerIP
        {
            get
            {
                 return serverIP;
            }
            set
            {
                 this.serverIP = value;
            }
        }
        private int port;
        public int Port
        {
            get
            {
                 return this.port;
            }
            set
            {
                 this.port = value;
            }
        }
        //delegate de set du lieu cho cac control
        public delegate void SetDataControl(string Data);
        public SetDataControl SetDataFunction = null;
        Socket serverSocket = null;
        IPEndPoint serverEP = null;
        Socket clientSocket = null;
        //buffer de nhan du lieu
        byte[] buff = new byte[1024];
        int byteReceive = 0;
        string stringReceive = "";
        public ServerProgram(IPAddress ServerIP, int Port)
        {
            this.ServerIP = ServerIP;
            this.Port = Port;
        }
        //lang nghe ket noi
        public void Listen()
        {
            serverSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
serverEP = new IPEndPoint(ServerIP, Port);
            //ket hop server socket voi local Endpoint
            serverSocket.Bind(serverEP);
            //lang nghe ket noi tren server socket
            //-1: ko gioi han so luong client ket noi den
            serverSocket.Listen(-1);
            SetDataFunction("dang cho ket noi");
            //bat dau chap nhan client ket noi den
            serverSocket.BeginAccept(new AsyncCallback(AcceptSocket),
serverSocket);

         }
         //ham callback chap nhan client ket noi
         private void AcceptSocket(IAsyncResult ia)
         {
             Socket s = (Socket)ia.AsyncState;
             //ham accept se block server lai va cho client ket noi den
             //sau khi client ket noi den se tra ve socket chua thong tin cua
client
            clientSocket = s.EndAccept(ia);
            string hello = "hello client";
            buff = Encoding.ASCII.GetBytes(hello);
            SetDataFunction("client" + clientSocket.RemoteEndPoint.ToString()
+ "da ket noi den");
            clientSocket.BeginSend(buff, 0, buff.Length, SocketFlags.None,
new AsyncCallback(SendData), clientSocket);

        }
        private void SendData(IAsyncResult ia)
        {
            Socket s = (Socket)ia.AsyncState;
            s.EndSend(ia);
            //khoi tao lai buffer de nhan du lieu
            buff = new byte[1024];
            //bat dau nhan dl
            s.BeginReceive(buff, 0, buff.Length, SocketFlags.None, new
AsyncCallback(ReceiveData), s);
        }
        public void Close()
        {
            clientSocket.Close();
            serverSocket.Close();
        }
        private void ReceiveData(IAsyncResult ia)
        {
            Socket s = (Socket)ia.AsyncState;
            try
            {
                byteReceive = s.EndReceive(ia);
            }
            catch
            {
                this.Close();
                SetDataFunction("client ngat ket noi");
                this.Listen();
                return;
            }
if(byteReceive == 0)
            {
                 Close();
                 SetDataFunction("client dong ket noi");
            }
            else
            {
                 stringReceive = Encoding.ASCII.GetString(buff, 0,
byteReceive);
                 SetDataFunction(stringReceive);
                 s.BeginSend(buff, 0, buff.Length, SocketFlags.None, new
AsyncCallback(SendData),s);
            }
        }
        static void Main(string[] args)
        {

          }
    }
}




Lớp serverForm
using   System;
using   System.Net.Sockets;
using   System.Net;
using   System.Collections.Generic;
using   System.ComponentModel;
using   System.Data;
using   System.Drawing;
using   System.Linq;
using   System.Text;
using   System.Windows.Forms;

namespace server
{
    public partial class serverForm : Form
    {
        ServerProgram server = new ServerProgram(IPAddress.Any, 6000);
        public serverForm()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            server.SetDataFunction = new
            ServerProgram.SetDataControl(SetData);
        }
        private void SetData(string Data)
        {
            this.listBox1.Items.Add(Data);
        }

          private void btn_start_Click(object sender, EventArgs e)
          {
server.Listen();
          }

          private void btn_stop_Click(object sender, EventArgs e)
          {
              this.server.Close();
              SetData("server dong ket noi");
          }

          private void serverForm_Load(object sender, EventArgs e)
          {

          }


    }
}




Lớ clientProgram
  p
using   System;
using   System.Net;
using   System.Net.Sockets;
using   System.Collections.Generic;
using   System.Linq;
using   System.Text;

namespace client
{
    class ClientProgram
    {
        //delegate de set du lieu cho cac control
        public delegate void SetDataControl(string Data);
        public SetDataControl SetDataFunction = null;
        //buffer de nhan va goi du lieu
        byte[] buff = new byte[1024];
        //so byte thuc su nhan dc
        int byteReceive = 0;
        //chuoi nhan dc
        string stringReceive = "";
        Socket serverSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint serverEP = null;
        //lang nghe ket noi
        public void Connect(IPAddress serverIP, int Port)
        {
            serverEP = new IPEndPoint(serverIP, Port);
            serverSocket.BeginConnect(serverEP, new
AsyncCallback(ConnectCallback), serverSocket);

          }
          private void ConnectCallback(IAsyncResult ia)
{
            Socket s = (Socket)ia.AsyncState;
            try
            {
                SetDataFunction("dang cho ket noi");
                s.EndConnect(ia);
                SetDataFunction("ket noi thanh cong");
            }
            catch
            {
                SetDataFunction("ket noi that bai");
                return;
            }
            s.BeginReceive(buff, 0, buff.Length, SocketFlags.None, new
AsyncCallback(ReceiveData), s);
        }
        private void ReceiveData(IAsyncResult ia)
        {
            Socket s = (Socket)ia.AsyncState;
            byteReceive = s.EndReceive(ia);
            stringReceive = Encoding.ASCII.GetString(buff, 0, byteReceive);
            SetDataFunction(stringReceive);
        }
        private void SendData(IAsyncResult ia)
        {
            Socket s = (Socket)ia.AsyncState;
            s.EndSend(ia);
            buff = new byte[1024];
            s.BeginReceive(buff, 0, buff.Length, SocketFlags.None, new
AsyncCallback(ReceiveData), s);
        }
        public bool Disconnect()
        {
            try
            {
                //shutdown socket dang ket noi den server
                serverSocket.Shutdown(SocketShutdown.Both);
                serverSocket.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public void SendData(string Data)
        {
            buff = Encoding.ASCII.GetBytes(Data);
            serverSocket.BeginSend(buff, 0, buff.Length, SocketFlags.None,
new AsyncCallback(SendToServer), serverSocket);
        }
        private void SendToServer(IAsyncResult ia)
        {
            Socket s = (Socket)ia.AsyncState;
            s.EndSend(ia);
            buff = new byte[1024];
s.BeginReceive(buff, 0, buff.Length, SocketFlags.None, new
AsyncCallback(ReceiveData), s);
        }
        static void Main(string[] args)
        {

          }

    }
}



Lớ clientForm
  p
using   System;
using   System.Net;
using   System.Net.Sockets;
using   System.Collections.Generic;
using   System.ComponentModel;
using   System.Data;
using   System.Drawing;
using   System.Linq;
using   System.Text;
using   System.Windows.Forms;

namespace client
{
    public partial class ClientForm : Form
    {
        ClientProgram client = new ClientProgram();
        public ClientForm()

          {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            client.SetDataFunction = new
ClientProgram.SetDataControl(SetData);
        }
        private void SetData(String Data)
        {
            this.listBox1.Items.Add(Data);
        }

        private void btn_connect_Click(object sender, EventArgs e)
        {
            client.Connect(IPAddress.Parse(this.txtserverIP.Text),
int.Parse(this.txtPort.Text));
        }

          private void btn_Dis_Click(object sender, EventArgs e)
          {
              client.Disconnect();
          }

          private void btn_send_Click(object sender, EventArgs e)
{
            client.SendData(this.txtInput.Text);
            this.txtInput.Text = "";
        }
    }
}

Mais conteúdo relacionado

Mais procurados

Chatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopChatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptop
yayaria
 
Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialProgramming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorial
Jeff Smith
 
Connecting to the network
Connecting to the networkConnecting to the network
Connecting to the network
Mu Chun Wang
 
Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介
Kiyotaka Oku
 

Mais procurados (18)

201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian201913001 khairunnisa progres_harian
201913001 khairunnisa progres_harian
 
Tugas 2
Tugas 2Tugas 2
Tugas 2
 
Reactive server with netty
Reactive server with nettyReactive server with netty
Reactive server with netty
 
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RIThe Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
The Ruby Guide to *nix Plumbing: on the quest for efficiency with Ruby [M|K]RI
 
Chatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptopChatting dengan beberapa pc laptop
Chatting dengan beberapa pc laptop
 
Paris Kafka Meetup - How to develop with Kafka
Paris Kafka Meetup - How to develop with KafkaParis Kafka Meetup - How to develop with Kafka
Paris Kafka Meetup - How to develop with Kafka
 
Abusing text/template for data transformation
Abusing text/template for data transformationAbusing text/template for data transformation
Abusing text/template for data transformation
 
Npc14
Npc14Npc14
Npc14
 
Using ngx_lua in UPYUN
Using ngx_lua in UPYUNUsing ngx_lua in UPYUN
Using ngx_lua in UPYUN
 
Programming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorialProgramming with ZooKeeper - A basic tutorial
Programming with ZooKeeper - A basic tutorial
 
Connecting to the network
Connecting to the networkConnecting to the network
Connecting to the network
 
Dpilot Source Code With ScreenShots
Dpilot Source Code With ScreenShots Dpilot Source Code With ScreenShots
Dpilot Source Code With ScreenShots
 
Source Code for Dpilot
Source Code for Dpilot Source Code for Dpilot
Source Code for Dpilot
 
Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介
 
#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG#JavaFX.forReal() - ElsassJUG
#JavaFX.forReal() - ElsassJUG
 
Netty: asynchronous data transfer
Netty: asynchronous data transferNetty: asynchronous data transfer
Netty: asynchronous data transfer
 
LibreSSL, one year later
LibreSSL, one year laterLibreSSL, one year later
LibreSSL, one year later
 
Whispered secrets
Whispered secretsWhispered secrets
Whispered secrets
 

Semelhante a Winform

Laporan multiclient chatting client server
Laporan multiclient chatting client serverLaporan multiclient chatting client server
Laporan multiclient chatting client server
trilestari08
 
I need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docxI need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docx
hendriciraida
 
I need an explaining for each step in this code and the reason of it-.docx
I need an explaining for each step in this code and the reason of it-.docxI need an explaining for each step in this code and the reason of it-.docx
I need an explaining for each step in this code and the reason of it-.docx
hendriciraida
 
TCP IP
TCP IPTCP IP
TCP IP
hivasu
 
Include- Modularity using design patterns- Fault tolerance and Compone.pdf
Include- Modularity using design patterns- Fault tolerance and Compone.pdfInclude- Modularity using design patterns- Fault tolerance and Compone.pdf
Include- Modularity using design patterns- Fault tolerance and Compone.pdf
RyanF2PLeev
 
Chapter 4 slides
Chapter 4 slidesChapter 4 slides
Chapter 4 slides
lara_ays
 

Semelhante a Winform (20)

java sockets
 java sockets java sockets
java sockets
 
Laporan multiclient chatting client server
Laporan multiclient chatting client serverLaporan multiclient chatting client server
Laporan multiclient chatting client server
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
 
I need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docxI need you to modify and change the loop in this code without changing.docx
I need you to modify and change the loop in this code without changing.docx
 
Arp
ArpArp
Arp
 
I need an explaining for each step in this code and the reason of it-.docx
I need an explaining for each step in this code and the reason of it-.docxI need an explaining for each step in this code and the reason of it-.docx
I need an explaining for each step in this code and the reason of it-.docx
 
Assignment Server, Client Application
Assignment Server, Client ApplicationAssignment Server, Client Application
Assignment Server, Client Application
 
Lecture6
Lecture6Lecture6
Lecture6
 
Client server part 12
Client server part 12Client server part 12
Client server part 12
 
Network programming1
Network programming1Network programming1
Network programming1
 
分散式系統
分散式系統分散式系統
分散式系統
 
#2 (UDP)
#2 (UDP)#2 (UDP)
#2 (UDP)
 
TCP IP
TCP IPTCP IP
TCP IP
 
Include- Modularity using design patterns- Fault tolerance and Compone.pdf
Include- Modularity using design patterns- Fault tolerance and Compone.pdfInclude- Modularity using design patterns- Fault tolerance and Compone.pdf
Include- Modularity using design patterns- Fault tolerance and Compone.pdf
 
Networking.ppt(client/server, socket) uses in program
Networking.ppt(client/server, socket) uses in programNetworking.ppt(client/server, socket) uses in program
Networking.ppt(client/server, socket) uses in program
 
Network security Lab manual
Network security Lab manual Network security Lab manual
Network security Lab manual
 
Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programming
 
Protocol-Oriented Networking
Protocol-Oriented NetworkingProtocol-Oriented Networking
Protocol-Oriented Networking
 
Chapter 4 slides
Chapter 4 slidesChapter 4 slides
Chapter 4 slides
 

Winform

  • 1. Lớp serverProgram using System; using System.Net; using System.Net.Sockets; using System.Collections.Generic; using System.Linq; using System.Text; namespace server { class ServerProgram { private IPAddress serverIP; public IPAddress ServerIP { get { return serverIP; } set { this.serverIP = value; } } private int port; public int Port { get { return this.port; } set { this.port = value; } } //delegate de set du lieu cho cac control public delegate void SetDataControl(string Data); public SetDataControl SetDataFunction = null; Socket serverSocket = null; IPEndPoint serverEP = null; Socket clientSocket = null; //buffer de nhan du lieu byte[] buff = new byte[1024]; int byteReceive = 0; string stringReceive = ""; public ServerProgram(IPAddress ServerIP, int Port) { this.ServerIP = ServerIP; this.Port = Port; } //lang nghe ket noi public void Listen() { serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  • 2. serverEP = new IPEndPoint(ServerIP, Port); //ket hop server socket voi local Endpoint serverSocket.Bind(serverEP); //lang nghe ket noi tren server socket //-1: ko gioi han so luong client ket noi den serverSocket.Listen(-1); SetDataFunction("dang cho ket noi"); //bat dau chap nhan client ket noi den serverSocket.BeginAccept(new AsyncCallback(AcceptSocket), serverSocket); } //ham callback chap nhan client ket noi private void AcceptSocket(IAsyncResult ia) { Socket s = (Socket)ia.AsyncState; //ham accept se block server lai va cho client ket noi den //sau khi client ket noi den se tra ve socket chua thong tin cua client clientSocket = s.EndAccept(ia); string hello = "hello client"; buff = Encoding.ASCII.GetBytes(hello); SetDataFunction("client" + clientSocket.RemoteEndPoint.ToString() + "da ket noi den"); clientSocket.BeginSend(buff, 0, buff.Length, SocketFlags.None, new AsyncCallback(SendData), clientSocket); } private void SendData(IAsyncResult ia) { Socket s = (Socket)ia.AsyncState; s.EndSend(ia); //khoi tao lai buffer de nhan du lieu buff = new byte[1024]; //bat dau nhan dl s.BeginReceive(buff, 0, buff.Length, SocketFlags.None, new AsyncCallback(ReceiveData), s); } public void Close() { clientSocket.Close(); serverSocket.Close(); } private void ReceiveData(IAsyncResult ia) { Socket s = (Socket)ia.AsyncState; try { byteReceive = s.EndReceive(ia); } catch { this.Close(); SetDataFunction("client ngat ket noi"); this.Listen(); return; }
  • 3. if(byteReceive == 0) { Close(); SetDataFunction("client dong ket noi"); } else { stringReceive = Encoding.ASCII.GetString(buff, 0, byteReceive); SetDataFunction(stringReceive); s.BeginSend(buff, 0, buff.Length, SocketFlags.None, new AsyncCallback(SendData),s); } } static void Main(string[] args) { } } } Lớp serverForm using System; using System.Net.Sockets; using System.Net; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace server { public partial class serverForm : Form { ServerProgram server = new ServerProgram(IPAddress.Any, 6000); public serverForm() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; server.SetDataFunction = new ServerProgram.SetDataControl(SetData); } private void SetData(string Data) { this.listBox1.Items.Add(Data); } private void btn_start_Click(object sender, EventArgs e) {
  • 4. server.Listen(); } private void btn_stop_Click(object sender, EventArgs e) { this.server.Close(); SetData("server dong ket noi"); } private void serverForm_Load(object sender, EventArgs e) { } } } Lớ clientProgram p using System; using System.Net; using System.Net.Sockets; using System.Collections.Generic; using System.Linq; using System.Text; namespace client { class ClientProgram { //delegate de set du lieu cho cac control public delegate void SetDataControl(string Data); public SetDataControl SetDataFunction = null; //buffer de nhan va goi du lieu byte[] buff = new byte[1024]; //so byte thuc su nhan dc int byteReceive = 0; //chuoi nhan dc string stringReceive = ""; Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint serverEP = null; //lang nghe ket noi public void Connect(IPAddress serverIP, int Port) { serverEP = new IPEndPoint(serverIP, Port); serverSocket.BeginConnect(serverEP, new AsyncCallback(ConnectCallback), serverSocket); } private void ConnectCallback(IAsyncResult ia)
  • 5. { Socket s = (Socket)ia.AsyncState; try { SetDataFunction("dang cho ket noi"); s.EndConnect(ia); SetDataFunction("ket noi thanh cong"); } catch { SetDataFunction("ket noi that bai"); return; } s.BeginReceive(buff, 0, buff.Length, SocketFlags.None, new AsyncCallback(ReceiveData), s); } private void ReceiveData(IAsyncResult ia) { Socket s = (Socket)ia.AsyncState; byteReceive = s.EndReceive(ia); stringReceive = Encoding.ASCII.GetString(buff, 0, byteReceive); SetDataFunction(stringReceive); } private void SendData(IAsyncResult ia) { Socket s = (Socket)ia.AsyncState; s.EndSend(ia); buff = new byte[1024]; s.BeginReceive(buff, 0, buff.Length, SocketFlags.None, new AsyncCallback(ReceiveData), s); } public bool Disconnect() { try { //shutdown socket dang ket noi den server serverSocket.Shutdown(SocketShutdown.Both); serverSocket.Close(); return true; } catch { return false; } } public void SendData(string Data) { buff = Encoding.ASCII.GetBytes(Data); serverSocket.BeginSend(buff, 0, buff.Length, SocketFlags.None, new AsyncCallback(SendToServer), serverSocket); } private void SendToServer(IAsyncResult ia) { Socket s = (Socket)ia.AsyncState; s.EndSend(ia); buff = new byte[1024];
  • 6. s.BeginReceive(buff, 0, buff.Length, SocketFlags.None, new AsyncCallback(ReceiveData), s); } static void Main(string[] args) { } } } Lớ clientForm p using System; using System.Net; using System.Net.Sockets; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace client { public partial class ClientForm : Form { ClientProgram client = new ClientProgram(); public ClientForm() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; client.SetDataFunction = new ClientProgram.SetDataControl(SetData); } private void SetData(String Data) { this.listBox1.Items.Add(Data); } private void btn_connect_Click(object sender, EventArgs e) { client.Connect(IPAddress.Parse(this.txtserverIP.Text), int.Parse(this.txtPort.Text)); } private void btn_Dis_Click(object sender, EventArgs e) { client.Disconnect(); } private void btn_send_Click(object sender, EventArgs e)
  • 7. { client.SendData(this.txtInput.Text); this.txtInput.Text = ""; } } }