C# Socket Programming
ไหมไทย :: C# Programming :: General
หน้า 1 จาก 1 • Share
C# Socket Programming
C# Socket Programming with SharpDevelop.

Download: http://www.icsharpcode.net/opensource/sd/download/
Create Server Socket.

1. File -> New -> Solution

Select “Windows Application” template and input project name “ServerSocket”.
Then click “Create” button.
2. Select the Design tab and create component from the tools.

3. Double click on the button component to accept on click action. All 3 buttons (Start, Stop, Send).
4. Switch to the Source tab and code.
Create Client Socket.

1. File -> New -> Solution

Select “Windows Application” template and input project name “ServerSocket”.
Then click “Create” button.
2. Select the Design tab and create component from the tools.

3. Double click on the button component to accept on click action. All 3 buttons (Connect, Disconnect, Send).
4. Switch to the Source tab and code.

Download: http://www.icsharpcode.net/opensource/sd/download/
Create Server Socket.

1. File -> New -> Solution

Select “Windows Application” template and input project name “ServerSocket”.
Then click “Create” button.
2. Select the Design tab and create component from the tools.

3. Double click on the button component to accept on click action. All 3 buttons (Start, Stop, Send).
4. Switch to the Source tab and code.
- Code:
/*
* Author: psupawa@gmail.com
* Date: 25-Jun-14
* Time: 11:22 AM
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace ServerSocket
{
/// <summary>
/// Demonstrate how to use windows socket in C#
/// </summary>
public partial class MainForm
{
[STAThread]
public static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
public MainForm()
{
// Initialize the component created in SharpDevelop form designer.
InitializeComponent();
// Initialize component value.
hostText.Text = GetHostIP();
workerSocket = new Socket[MAX_CLIENTS];
availableSocket = new bool[MAX_CLIENTS];
clientIP = new String[MAX_CLIENTS];
for (int i=0; i<availableSocket.Length; i++) {
availableSocket[i] = true;
}
}
private AsyncCallback workerCallBack ;
private Socket mainSocket;
private Socket[] workerSocket;
private int clientIndex = 0;
private const int MAX_CLIENTS = 10;
private bool[] availableSocket;
private String[] clientIP;
private void OpenButtonClick(object sender, System.EventArgs e)
{
try {
// Check the port value
if (portText.Text == "") {
statusText.AppendText("Please enter a Port Number\n");
return;
}
string portStr = portText.Text;
int port = System.Convert.ToInt32(portStr);
// Create the listening socket...
mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint (IPAddress.Any, port);
// Bind to local IP Address
mainSocket.Bind(ipLocal);
// Start listening
mainSocket.Listen(4);
// Create the call back for client connections
statusText.AppendText("Server is listening on port " + portStr + "\n");
mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
UpdateControls(true);
closeButton.Focus();
}
catch(SocketException ex) {
statusText.AppendText("Error: " + ex.Message + "\n");
}
}
private void CloseButtonClick(object sender, System.EventArgs e)
{
if (mainSocket != null) {
mainSocket.Close();
}
for (int i = 0; i < workerSocket.Length; i++) {
if (workerSocket[i] != null) {
workerSocket[i].Close();
workerSocket[i] = null;
}
}
UpdateControls(false);
inText.Clear();
outText.Clear();
statusText.Clear();
sendButton.Enabled = false;
}
private void UpdateControls(bool listening)
{
openButton.Enabled = !listening;
closeButton.Enabled = listening;
portText.Enabled = !listening;
inText.Enabled = listening;
outText.Enabled = listening;
}
// This is the call back function, which will be invoked when a client is connected
private void OnClientConnect(IAsyncResult asyn)
{
try {
// Find available socket
for (int i=0; i<availableSocket.Length; i++) {
if (availableSocket[i]) {
clientIndex = i;
availableSocket[i] = false;
}
}
// Accept new client connection and assign to the workerSocket
workerSocket[clientIndex] = mainSocket.EndAccept(asyn);
clientIP[clientIndex] = workerSocket[clientIndex].RemoteEndPoint.ToString();
// Display this client connection
statusText.AppendText("Client connected, " + clientIP[clientIndex] + "\n");
// Let the worker Socket do the further processing for the just connected client
WaitForData(workerSocket[clientIndex]);
sendButton.Enabled = true;
inText.Focus();
// The main Socket is now free and waiting for new client conection
mainSocket.BeginAccept(new AsyncCallback (OnClientConnect ),null);
}
catch(ObjectDisposedException) {
// Ignore error, when socket disposed
}
catch(SocketException ex) {
statusText.AppendText(ex.Message + "\n");
}
}
// Waiting for data from client
private void WaitForData(Socket soc)
{
try
{
if ( workerCallBack == null ){
// Invoke the call back function when client send data
workerCallBack = new AsyncCallback(OnDataReceived);
}
SocketPacket socketPacket = new SocketPacket();
socketPacket.currentSocket = soc;
// Start receiving data from client, asynchronously
soc.BeginReceive (
socketPacket.dataBuffer,
0,
socketPacket.dataBuffer.Length,
SocketFlags.None,
workerCallBack,
socketPacket
);
}
catch(SocketException ex) {
// Display execption message
statusText.AppendText("WaitForData, error: " + ex.Message + "\n");
}
}
// A call back function invoked when the socket detects incoming data on the stream
private void OnDataReceived(IAsyncResult asyn)
{
EndPoint hostID = null;
try {
SocketPacket socketData = (SocketPacket)asyn.AsyncState;
hostID = socketData.currentSocket.RemoteEndPoint;
int iRx = 0 ;
// Receive data
iRx = socketData.currentSocket.EndReceive(asyn);
char[] chars = new char[iRx + 1];
Decoder d = Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(socketData.dataBuffer, 0, iRx, chars, 0);
String szData = new String(chars);
inText.AppendText(szData);
// Continue the waiting for data on the Socket
WaitForData(socketData.currentSocket);
}
catch(ObjectDisposedException) {
// Ignore error, when socket disposed
}
catch(SocketException) {
// Client disconnect
sendButton.Enabled = false;
for (int i=0; i<clientIP.Length; i++) {
if (clientIP[i] == hostID.ToString()) {
statusText.AppendText("Client disconnected, " + hostID + "\n");
availableSocket[i] = true;
clientIP[i] = "";
}
}
}
}
private class SocketPacket
{
public Socket currentSocket;
public byte[] dataBuffer = new byte[1];
}
private void SendButtonClick(object sender, System.EventArgs e)
{
try {
Object objData = outText.Text + "\n";
byte[] byData = Encoding.ASCII.GetBytes(objData.ToString());
for (int i = 0; i < workerSocket.Length; i++) {
if (workerSocket[i] != null) {
if (workerSocket[i].Connected) {
workerSocket[i].Send (byData);
}
}
}
}
catch(SocketException ex) {
statusText.AppendText("Error" + ex.Message + "\n");
}
}
private String GetHostIP()
{
String strHostName = Dns.GetHostName();
// Find host by name
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
// Grab the first IP addresses
String IPStr = addr[addr.Length-1].ToString();
return IPStr;
}
}
}
Create Client Socket.

1. File -> New -> Solution

Select “Windows Application” template and input project name “ServerSocket”.
Then click “Create” button.
2. Select the Design tab and create component from the tools.

3. Double click on the button component to accept on click action. All 3 buttons (Connect, Disconnect, Send).
4. Switch to the Source tab and code.
- Code:
/*
* Author: psupawa@gmail.com
* Date: 25-Jun-14
* Time: 4:07 PM
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace ClientSocket
{
/// <summary>
/// Description of MainForm.
/// </summary>
public partial class MainForm
{
[STAThread]
public static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
public MainForm()
{
// Initialize the component created in SharpDevelop form designer.
InitializeComponent();
// Initialize component value.
hostText.Text = GetHostIP();
}
private byte[] dataBuffer = new byte[10];
private IAsyncResult result;
private AsyncCallback asyncCallBack ;
private Socket clientSocket;
private void OpenButtonClick(object sender, EventArgs eventArgs)
{
// See if there are text input for the Host and Port text fields
if (hostText.Text == "" || portText.Text == "") {
statusText.Text = "Host Address and Port Number are required\n";
return;
}
statusText.Text = "Trying connection, please wait..\n";
this.Cursor = Cursors.WaitCursor;
try {
UpdateControls(false);
// Create the socket instance
clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Cet the remote IP address
IPAddress ip = IPAddress.Parse(hostText.Text);
int iPortNo = Convert.ToInt16(portText.Text);
// Create the end point
IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
// Connect to the remote host
clientSocket.Connect(ipEnd);
if(clientSocket.Connected) {
UpdateControls(true);
WaitForData();
}
statusText.Text = "Connection success\n";
inText.Clear();
outText.Clear();
outText.Focus();
}
catch(SocketException ex) {
UpdateControls(false);
statusText.AppendText("Error: " + ex.Message + "\n");
}
this.Cursor = Cursors.Default;
}
private void CloseButtonClick(object sender, EventArgs eventArgs)
{
PerformCloseAction("Disconnected");
}
private void PerformCloseAction(String message)
{
if (clientSocket != null) {
clientSocket.Close();
clientSocket = null;
UpdateControls(false);
}
statusText.Text = message;
inText.Clear();
outText.Clear();
openButton.Focus();
}
private void SendButtonClick(object sender, EventArgs eventArgs)
{
try {
Object objData = outText.Text + "\n";
byte[] byData = Encoding.ASCII.GetBytes(objData.ToString());
if(clientSocket != null){
clientSocket.Send (byData);
}
}
catch(SocketException ex) {
statusText.AppendText("SendButtonClick, error: " + ex.Message + "\n");
}
}
public void WaitForData()
{
try {
if (asyncCallBack == null) {
asyncCallBack = new AsyncCallback(OnDataReceived);
}
SocketPacket socketPacket = new SocketPacket();
socketPacket.thisSocket = clientSocket;
// Start listening to the data asynchronously
result = clientSocket.BeginReceive (
socketPacket.dataBuffer,
0,
socketPacket.dataBuffer.Length,
SocketFlags.None,
asyncCallBack,
socketPacket
);
}
catch(SocketException ex) {
statusText.AppendText("WaitForData, error: " + ex.Message + "\n");
}
}
private class SocketPacket
{
public Socket thisSocket;
public byte[] dataBuffer = new byte[1];
}
private void OnDataReceived(IAsyncResult asyn)
{
try {
SocketPacket theSockId = (SocketPacket)asyn.AsyncState ;
int iRx = theSockId.thisSocket.EndReceive (asyn);
char[] chars = new char[iRx + 1];
Decoder d = Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
String szData = new String(chars);
inText.AppendText(szData);
WaitForData();
}
catch (ObjectDisposedException) {
// The socket has been closed, ignore action
}
catch(SocketException ex) {
http://MessageBox.Show(ex.Message);
statusText.AppendText("OnDataReceived, error: " + ex.Message + "\n");
PerformCloseAction(ex.Message);
}
}
private void UpdateControls( bool connected )
{
openButton.Enabled = !connected;
closeButton.Enabled = connected;
sendButton.Enabled = connected;
hostText.Enabled = !connected;
portText.Enabled = !connected;
inText.Enabled = connected;
outText.Enabled = connected;
}
private String GetHostIP()
{
String strHostName = Dns.GetHostName();
// Find host by name
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
// Grab the first IP addresses
String IPStr = addr[addr.Length-1].ToString();
return IPStr;
}
}
}
ไหมไทย :: C# Programming :: General
หน้า 1 จาก 1
Permissions in this forum:
คุณไม่สามารถพิมพ์ตอบ
|
|