C#how to implement socket connection in windows phone 7 using
انا اعمل بمشروع تخرج على wp7 واريد ان اعمل concretion using socket بين wp بواسطة C# وبرنامج السيرفر الذي قمت بعمله عن طريق Vb.net وسوف ارفق الكود ارجوا المساعدة ولكم جزيل الشكر
جزاكم الله خيرا .
Main page code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
// Constants
namespace PhoneApp3
{
public partial class MainPage : PhoneApplicationPage
{
const int ECHO_PORT = 63000; // The Echo protocol uses port 7 in this sample
const int QOTD_PORT = 63000; // The Quote of the Day (QOTD) protocol uses port 17 in this sample
// Constructor
public MainPage()
{
InitializeComponent();
}
/// <summary>
/// Handle the btnEcho_Click event by sending text to the echo server and outputting the response
/// </summary>
private void btnEcho_Click(object sender, RoutedEventArgs e)
{
// Clear the log
ClearLog();
// Make sure we can perform this action with valid data
if (ValidateRemoteHost() && ValidateInput())
{
// Instantiate the SocketClient
SocketClient client = new SocketClient();
// Attempt to connect to the echo server
Log(String.Format("Connecting to server '{0}' over port {1} (echo) ...", txtRemoteHost.Text, ECHO_PORT), true);
string result = client.Connect(txtRemoteHost.Text, ECHO_PORT);
Log(result, false);
// Attempt to send our message to be echoed to the echo server
Log(String.Format("Sending '{0}' to server ...", txtInput.Text), true);
result = client.Send(txtInput.Text);
Log(result, false);
// Receive a response from the echo server
Log("Requesting Receive ...", true);
result = client.Receive();
Log(result, false);
// Close the socket connection explicitly
client.Close();
}
}
/// <summary>
/// Handle the btnEcho_Click event by receiving text from the Quote of the Day (QOTD) server and outputting the response
/// </summary>
private void btnGetQuote_Click(object sender, RoutedEventArgs e)
{
// Clear the log
ClearLog();
// Make sure we can perform this action with valid data
if (ValidateRemoteHost())
{
// Instantiate the SocketClient object
SocketClient client = new SocketClient();
// Attempt connection to the Quote of the Day (QOTD) server
Log(String.Format("Connecting to server '{0}' over port {1} (Quote of the Day) ...", txtRemoteHost.Text, QOTD_PORT), true);
string result = client.Connect(txtRemoteHost.Text, QOTD_PORT);
Log(result, false);
// Note: The QOTD protocol is not expecting data to be sent to it. So we omit a
// send call in this example.
// Receive response from the QOTD server
Log("Requesting Receive ...", true);
result = client.Receive();
Log(result, false);
// Close the socket conenction explicitly
client.Close();
}
}
#region UI Validation
/// <summary>
/// Validates the txtInput TextBox
/// </summary>
/// <returns>True if the txtInput TextBox contains valid data, False otherwise</returns>
private bool ValidateInput()
{
// txtInput must contain some text
if (String.IsNullOrWhiteSpace(txtInput.Text))
{
MessageBox.Show("Please enter some text to echo");
return false;
}
return true;
}
/// <summary>
/// Validates the txtRemoteHost TextBox
/// </summary>
/// <returns>True if the txtRemoteHost contains valid data, False otherwise</returns>
private bool ValidateRemoteHost()
{
// The txtRemoteHost must contain some text
if (String.IsNullOrWhiteSpace(txtRemoteHost.Text))
{
MessageBox.Show("Please enter a host name");
return false;
}
return true;
}
#endregion
#region Logging
/// <summary>
/// Log text to the txtOutput TextBox
/// </summary>
/// <param name="message">The message to write to the txtOutput TextBox</param>
/// <param name="isOutgoing">True if the message is an outgoing (client to server) message, False otherwise</param>
/// <remarks>We differentiate between a message from the client and server
/// by prepending each line with ">>" and "<<" respectively.</remarks>
private void Log(string message, bool isOutgoing)
{
string direction = (isOutgoing) ? ">> " : "<< ";
txtOutput.Text += Environment.NewLine + direction + message;
}
/// <summary>
/// Clears the txtOutput TextBox
/// </summary>
private void ClearLog()
{
txtOutput.Text = String.Empty;
}
#endregion
}
}
Class code
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Net.Sockets;
using System.Threading;
using System.Text;
namespace PhoneApp3
{
public class SocketClient
{
// Cached Socket object that will be used by each call for the lifetime of this class
Socket _socket = null;
// Signaling object used to notify when an asynchronous operation is completed
static ManualResetEvent _clientDone = new ManualResetEvent(false);
// Define a timeout in milliseconds for each asynchronous call. If a response is not received within this
// timeout period, the call is aborted.
const int TIMEOUT_MILLISECONDS = 5000;
// The maximum size of the data buffer to use with the asynchronous socket methods
const int MAX_BUFFER_SIZE = 2048;
/// <summary>
/// Attempt a TCP socket connection to the given host over the given port
/// </summary>
/// <param name="hostName">The name of the host</param>
/// <param name="portNumber">The port number to connect</param>
/// <returns>A string representing the result of this connection attempt</returns>
public string Connect(string hostName, int portNumber)
{
string result = string.Empty;
// Create DnsEndPoint. The hostName and port are passed in to this method.
DnsEndPoint hostEntry = new DnsEndPoint(hostName, portNumber);
// Create a stream-based, TCP socket using the InterNetwork Address Family.
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Create a SocketAsyncEventArgs object to be used in the connection request
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = hostEntry;
// Inline event handler for the Completed event.
// Note: This event handler was implemented inline in order to make this method self-contained.
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
// Retrieve the result of this request
result = e.SocketError.ToString();
// Signal that the request is complete, unblocking the UI thread
_clientDone.Set();
});
// Sets the state of the event to nonsignaled, causing threads to block
_clientDone.Reset();
// Make an asynchronous Connect request over the socket
_socket.ConnectAsync(socketEventArg);
// Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
// If no response comes back within this time then proceed
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
return result;
}
/// <summary>
/// Send the given data to the server using the established connection
/// </summary>
/// <param name="data">The data to send to the server</param>
/// <returns>The result of the Send request</returns>
public string Send(string data)
{
string response = "Operation Timeout";
// We are re-using the _socket object that was initialized in the Connect method
if (_socket != null)
{
// Create SocketAsyncEventArgs context object
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
// Set properties on context object
socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
socketEventArg.UserToken = null;
// Inline event handler for the Completed event.
// Note: This event handler was implemented inline in order to make this method self-contained.
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
response = e.SocketError.ToString();
// Unblock the UI thread
_clientDone.Set();
});
// Add the data to be sent into the buffer
byte[] payload = Encoding.UTF8.GetBytes(data);
socketEventArg.SetBuffer(payload, 0, payload.Length);
// Sets the state of the event to nonsignaled, causing threads to block
_clientDone.Reset();
// Make an asynchronous Send request over the socket
_socket.SendAsync(socketEventArg);
// Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
// If no response comes back within this time then proceed
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
}
else
{
response = "Socket is not initialized";
}
return response;
}
/// <summary>
/// Receive data from the server using the established socket connection
/// </summary>
/// <returns>The data received from the server</returns>
public string Receive()
{
string response = "Operation Timeout";
// We are receiving over an established socket connection
if (_socket != null)
{
// Create SocketAsyncEventArgs context object
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
// Setup the buffer to receive the data
socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
// Inline event handler for the Completed event.
// Note: This even handler was implemented inline in order to make this method self-contained.
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
// Retrieve the data from the buffer
response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
response = response.Trim('\0');
}
else
{
response = e.SocketError.ToString();
}
_clientDone.Set();
});
// Sets the state of the event to nonsignaled, causing threads to block
_clientDone.Reset();
// Make an asynchronous Receive request over the socket
_socket.ReceiveAsync(socketEventArg);
// Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
// If no response comes back within this time then proceed
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
}
else
{
response = "Socket is not initialized";
}
return response;
}
/// <summary>
/// Closes the Socket connection and releases all associated resources
/// </summary>
public void Close()
{
if (_socket != null)
{
_socket.Close();
}
}
}
}
server code
Imports System.Net
Imports System.Net.Sockets
Imports System.IO
Imports System.Threading
Public Class Form1
Dim ipAddress As IPAddress = Dns.Resolve(Dns.GetHostName()).AddressList(0)
Dim trlisten As Thread
Dim result As String = "nothing recived"
Dim receivedData As String
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
trlisten = New Thread(AddressOf ListenToServer)
trlisten.Start()
End Sub
Sub ListenToServer()
Dim LISTENING As Boolean
Dim localhostAddress As IPAddress = ipAddress.Parse(ipAddress.ToString)
Dim port As Integer = 63000
Dim tcpList As New TcpListener(localhostAddress, port)
Try
tcpList.Start()
LISTENING = True
Do While LISTENING
Do While tcpList.Pending = False And LISTENING = True
Thread.Sleep(10)
Loop
If Not LISTENING Then Exit Do
Dim tcpCli As TcpClient = tcpList.AcceptTcpClient()
Dim ns As NetworkStream = tcpCli.GetStream
Dim sr As New StreamReader(ns)
''''''''''''''''''
'''''''''''''''''
receivedData = sr.ReadLine()
Label1.Text = receivedData
If receivedData = "REBOOT" Then
Shell("ping 192.168.1.1")
ElseIf receivedData = "LOGOFF" Then
Shell("shutdown /l ")
ElseIf receivedData = "hi" Then
result = " whats up "
ElseIf receivedData = "" Then
result = " whats "
End If
Dim returnedData As String = result
Dim sw As New StreamWriter(ns)
sw.WriteLine(returnedData)
Label2.Text = returnedData
sw.Flush()
sr.Close()
sw.Close()
ns.Close()
tcpCli.Close()
result = ""
returnedData = ""
Loop
tcpList.Stop()
receivedData = ""
Catch ex As Exception
LISTENING = False
End Try
End Sub
Private Sub Label1_Click(sender As System.Object, e As System.EventArgs) Handles Label1.Click
End Sub
End Class