废话不多说 直接上代码
服务端:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace SocketServer
{
public delegate void DelLink(string strTemp , string strTemp1);
public delegate void TextShowHandeler(string Message);
public partial class FormServer : Form
{
private Asy asyTemp = new Asy();
private DelLink linkSocket;
public FormServer()
{
InitializeComponent();
linkSocket = new DelLink(asyTemp.BeginAccept);
asyTemp.tshMessage += new TextShowHandeler(this.Appendtext);
}
private void buttonOk_Click(object sender, EventArgs e)
{
string IP = this.textBoxIp.Text;
string Port = this.textBoxPort.Text;
this.buttonOk.Enabled = false;
linkSocket.BeginInvoke(IP, Port, null, null);
}
private void buttonCancle_Click(object sender, EventArgs e)
{
this.Close();
}
public void Appendtext(string Message)
{
if (this.textBoxReceive.InvokeRequired)
{
//this.Invoke(asyTemp.tshMessage(Message));
TextShowHandeler d = new TextShowHandeler(Appendtext);
this.Invoke(d, new object[] { Message });
}
else
{
this.textBoxReceive.AppendText(Message);
if (Message.Length > 30)
{
this.toolStripStatusLabelSee.Text = Message.Remove(30) + "...";
}
else
{
this.toolStripStatusLabelSee.Text = Message;
}
}
}
private void FormServer_Load(object sender, EventArgs e)
{
}
}
public class Asy
{
public TextShowHandeler tshMessage;
public void BeginAccept(string IP , string Port)
{
int BUFFERSIZE = 256;
byte[] buffer = new byte[BUFFERSIZE];
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse(IP), int.Parse(Port));
server.Bind(iep);
server.Listen(5);
while (true)
{
IAsyncResult result = server.BeginAccept(new AsyncCallback(AcceptConn1), server);
this.tshMessage("waiting for a connection...\n");
result.AsyncWaitHandle.WaitOne();
}
}
public void AcceptConn1(IAsyncResult iar)
{
this.tshMessage("a socket is connected...\n");
Socket s = (Socket)iar.AsyncState;
Socket handler = s.EndAccept(iar);
StateObject state = new StateObject();
state.worksocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallBack), state);
}
public void ReadCallBack(IAsyncResult ar)
{
string content = string.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.worksocket;
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));
content = state.sb.ToString();
this.tshMessage("Read " + content.Length + " bytes from socket. \n");
this.tshMessage("Data:" + content + "\n");
Send(handler, content);
}
else
{
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallBack), state);
}
}
private void Send(Socket handler, String data)
{
byte[] bytedata = Encoding.UTF8.GetBytes(data);
handler.BeginSend(bytedata, 0, bytedata.Length, 0, new AsyncCallback(SendCallBack), handler);
}
private void SendCallBack(IAsyncResult ar)
{
try
{
Socket handler = (Socket)ar.AsyncState;
int bytesSent = handler.EndSend(ar);
this.tshMessage("Sent " + bytesSent + " bytes to client.\n");
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
this.tshMessage(e.ToString()+"\n");
}
}
}
public class StateObject
{
public Socket worksocket = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
}
客户端:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace SocketClient
{
public delegate void DelLink(string strTemp ,string strTemp1 ,string strTemp2);
public delegate void TextShowHandler(string strTemp);
public partial class FormClient : Form
{
private Asy asyTemp = new Asy();
private DelLink linkSocket;
public FormClient()
{
InitializeComponent();
linkSocket = new DelLink(asyTemp.BeginAccept);
asyTemp.tshMessage = new TextShowHandler(this.AppendText);
}
// The response from the remote device.
private static String response = String.Empty;
private void buttonSend_Click(object sender, EventArgs e)
{
string IP = this.textBoxIP.Text;
string Port = this.textBoxPort.Text;
string Message = this.textBoxMessage.Text;
this.linkSocket.BeginInvoke(IP, Port, Message , null , null);
}
public void AppendText(string Message)
{
if (textBoxMessage.InvokeRequired)
{
TextShowHandler d = new TextShowHandler(this.AppendText);
this.Invoke(d, new Object[] { Message });
}
else
{
this.textBoxMessage.AppendText(Message);
if (Message.Length > 30)
{
this.toolStripStatusLabelSee.Text = Message.Remove(30) + "...";
}
else
{
this.toolStripStatusLabelSee.Text = Message;
}
}
}
}
public class Asy
{
public TextShowHandler tshMessage;
public void BeginAccept(string IP , string Port , string Message)
{
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse(IP), int.Parse(Port));
IAsyncResult result = newsock.BeginConnect(iep, new AsyncCallback(ConnectCallback), newsock);
result.AsyncWaitHandle.WaitOne();
this.tshMessage("连上了主机.....\n");
Send(newsock, Message);
Receive(newsock);
//MessageBox.Show("回复信息为:"+response);
//newsock.Shutdown(SocketShutdown.Both);
//newsock.Close();
}
private void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
this.tshMessage("Socket connected to "+client.RemoteEndPoint.ToString() + "\n");
// Signal that the connection has been made.
}
catch (Exception e)
{
this.tshMessage(e.ToString());
}
}
private void Send(Socket client, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.UTF8.GetBytes(data);
// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), client);
}
private void 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);
this.tshMessage("Sent "+bytesSent+" bytes to server.\n");
// Signal that all bytes have been sent.
}
catch (Exception e)
{
this.tshMessage(e.ToString());
}
}
private void Receive(Socket client)
{
try
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
this.tshMessage(e.ToString());
}
}
private void ReceiveCallback(IAsyncResult ar)
{
try
{
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.UTF8.GetString(state.buffer, 0, bytesRead));
// Get the rest of the data.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
// All the data has arrived; put it in response.
if (state.sb.Length > 1)
{
string response = state.sb.ToString();
this.tshMessage("返回的信息为:" + response + "\n");
}
// Signal that all bytes have been received.
}
}
catch (Exception e)
{
this.tshMessage(e.ToString());
}
}
}
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
}