Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 29th, 2012  |  syntax: None  |  size: 1.57 KB  |  hits: 44  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. C# socket server with windows form application
  2. using System;
  3. using System.Collections.Generic;
  4. using System.ComponentModel;
  5. using System.Data;
  6. using System.Drawing;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Windows.Forms;
  10. using System.Net;
  11. using System.Net.Sockets;
  12. using System.Threading;
  13.  
  14. namespace mserver1
  15. {
  16.     public partial class Form1 : Form
  17.     {
  18.         public Form1()
  19.         {
  20.             InitializeComponent();
  21.         }
  22.  
  23.         private void button1_Click(object sender, EventArgs e)
  24.         {
  25.             ServerClass sc = new ServerClass();
  26.             sc.startServer(textBox1, richTextBox1);
  27.         }
  28.     }
  29.  
  30.  
  31.     public class ServerClass
  32.     {
  33.         public void startServer(TextBox tb, RichTextBox rb)
  34.         {
  35.  
  36.             IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9939);
  37.             Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  38.  
  39.             socket.Bind(ip);
  40.             socket.Listen(20);
  41.             rb.Text = rb.Text + "Waiting for client...";
  42.             Socket client = socket.Accept();
  43.             IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
  44.  
  45.             rb.Text = rb.Text + "Connected with " + clientep.Address + " at port " + clientep.Port;
  46.  
  47.             string welcome = tb.Text;
  48.             byte[] data = new byte[1024];
  49.             data = Encoding.ASCII.GetBytes(welcome);
  50.             client.Send(data, data.Length, SocketFlags.None);
  51.  
  52.             rb.Text = rb.Text + "Disconnected from" + clientep.Address;
  53.             client.Close();
  54.             socket.Close();
  55.         }
  56.     }
  57. }