服务器端代码:
///监听
private void listen()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[2048]; // Create a TCP/IP socket.
listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(localIpe);
listener.Listen(100);
Thread _acceptWorkThread = new Thread(AcceptWorkThread);
_acceptWorkThread.Start();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
} }
private void AcceptWorkThread()
{
while (true)
{
//allDone.Reset(); Socket socket= listener.Accept();
// Wait until a connection is made before continuing.
// Create the state object.
StateObject state = new StateObject();
state.workSocket = socket;
socket.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None,
ReadCallback, state);
}
}
/// <summary>
/// 异步处理函数
/// </summary>
/// <param name="ar"></param>
public void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(
state.buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString(); //检查报文长度
if (content.Length > 0)
{
MessageBox.Show("收到消息:"+content);
//this.textBox1.Text += content;
} else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
}
客户端处理函数,连接服务器,向服务器发送报文,每次发送完报文后,必须重新连接,才能发送报文:
/// <summary>
/// 连接服务器
/// </summary>
public void connectSev()
{
ClientThread = new Thread(new ThreadStart(StartClient));
ClientThread.Start();
} public void StartClient()
{
// Connect to a remote device.
try
{
// Create a TCP/IP socket.
Sockclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
Sockclient.BeginConnect(remoteipe, new AsyncCallback(ConnectCallback), Sockclient);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
/// <summary>
/// 连接回调函数
/// </summary>
/// <param name="ar"></param>
private void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
Console.WriteLine("Socket connected to {0}",
client.RemoteEndPoint.ToString());
// Signal that the connection has been made.
connectDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
/// <summary>
/// 发送报文
/// </summary>
/// <param name="client"></param>
/// <param name="data"></param>
public void ClientSend(Socket client, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(Client_SendCallback), client);
}
/// <summary>
/// 发送回调方式
/// </summary>
/// <param name="ar"></param>
private static void Client_SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", bytesSent);
// Signal that all bytes have been sent.
sendDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
///监听
private void listen()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[2048]; // Create a TCP/IP socket.
listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(localIpe);
listener.Listen(100);
Thread _acceptWorkThread = new Thread(AcceptWorkThread);
_acceptWorkThread.Start();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
} }
private void AcceptWorkThread()
{
while (true)
{
//allDone.Reset(); Socket socket= listener.Accept();
// Wait until a connection is made before continuing.
// Create the state object.
StateObject state = new StateObject();
state.workSocket = socket;
socket.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None,
ReadCallback, state);
}
}
/// <summary>
/// 异步处理函数
/// </summary>
/// <param name="ar"></param>
public void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(
state.buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString(); //检查报文长度
if (content.Length > 0)
{
MessageBox.Show("收到消息:"+content);
//this.textBox1.Text += content;
} else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
}
客户端处理函数,连接服务器,向服务器发送报文,每次发送完报文后,必须重新连接,才能发送报文:
/// <summary>
/// 连接服务器
/// </summary>
public void connectSev()
{
ClientThread = new Thread(new ThreadStart(StartClient));
ClientThread.Start();
} public void StartClient()
{
// Connect to a remote device.
try
{
// Create a TCP/IP socket.
Sockclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
Sockclient.BeginConnect(remoteipe, new AsyncCallback(ConnectCallback), Sockclient);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
/// <summary>
/// 连接回调函数
/// </summary>
/// <param name="ar"></param>
private void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
Console.WriteLine("Socket connected to {0}",
client.RemoteEndPoint.ToString());
// Signal that the connection has been made.
connectDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
/// <summary>
/// 发送报文
/// </summary>
/// <param name="client"></param>
/// <param name="data"></param>
public void ClientSend(Socket client, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(Client_SendCallback), client);
}
/// <summary>
/// 发送回调方式
/// </summary>
/// <param name="ar"></param>
private static void Client_SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", bytesSent);
// Signal that all bytes have been sent.
sendDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
我把接收报文处理那一块改称这样:
//检查报文长度
if (content.IndexOf("@")>0)
{
MessageBox.Show("收到消息:"+content);
state = (StateObject)ar.AsyncState;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
改后,可以连续发送和接收报文,但是每次接收到的报文是本次连接从开始到最后一次输入的字符串,比如第一次发送abcd@,收到后,在输入12345@,则第二次收到的是abcd@12345@,怎么让第二次收到的内容不包括前一次发送的。