PS: dưới đây là một đoạn code kết nối đến ứng dụng server khi click button connect.
Code:
public class SocketPacket
{
public Socket thisSocket;
public byte[] dataBuffer = new byte[1024];
}
private void UpdateControls(bool connected)
{
btn_Connect.Enabled = !connected;
btn_Disconnect.Enabled = connected;
string connectStatus = connected ? "Connected" : "Not Connected";
txt_ConnectionStatus.Text = connectStatus;
}
public 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);
//bị báo lỗi NotSupportException
txt_MsgReceived.Text = txt_MsgReceived.Text + szData();
WaitForData();
}
catch (ObjectDisposedException)
{
//System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
public void WaitForData()
{
try
{
if (m_pfnCallBack == null)
{
m_pfnCallBack = new AsyncCallback(OnDataReceived);
}
SocketPacket theSocPkt = new SocketPacket();
theSocPkt.thisSocket = m_clientSocket;
// Start listening to the data asynchronously
m_result = m_clientSocket.BeginReceive(theSocPkt.dataBuffer,
0, theSocPkt.dataBuffer.Length,
SocketFlags.None,
m_pfnCallBack,
theSocPkt);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
private void btn_Connect_Click(object sender, EventArgs e)
{
// See if we have text on the IP and Port text fields
if (txt_ServerIPAddress.Text == "" || txt_ServerPort.Text == "")
{
MessageBox.Show("IP Address and Port Number are required to connect to the Server\n");
return;
}
try
{
UpdateControls(false);
// Create the socket instance
m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Set the remote IP address
IPAddress ip = IPAddress.Parse(txt_ServerIPAddress.Text);
int iPortNo = Convert.ToInt16(txt_ServerPort.Text);
// Create the end point
IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo);
// Connect to the remote host
m_clientSocket.Connect(ipEnd);
if (m_clientSocket.Connected)
{
UpdateControls(true);
//Wait for data asynchronously
WaitForData();
}
}
catch (SocketException se)
{
string str;
str = "\nConnection failed, is the server running?\n" + se.Message;
MessageBox.Show(str);
UpdateControls(false);
}
}
Trên PC thì mình chạy ok, khi tạo một project trên smart device, copy code qua. Chỉ khác là chỗ bị báo lỗi thì trên PC dùng richtextbox, còn ứng dụng chạy trên smart device thì không có control đó nên dùng textbox thay vào!
Giúp @markpq với....!!!