您的位置:首页 > 编程语言 > C#

c# socket 异步

2016-03-24 21:31 381 查看
http://download.csdn.net/detail/qq_15572445/9471828

客户端:using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Socket_Client_asynchronous
{
public partial class Form1 : Form
{
public TcpClient tcpc; //对服务器端建立TCP连接
public Socket tcpsend; //发送创建套接字
public bool connect_flag = false;
public byte[] receive_buff = new byte[4096];
public ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号
public ManualResetEvent readDone = new ManualResetEvent(false); //读信号
public ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束
public bool connect(string address)
{
try
{
tcpsend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//初始化套接字
IPEndPoint remotepoint = new IPEndPoint(IPAddress.Parse(address), Convert.ToInt32(textBox3.Text));//根据ip地址和端口号创建远程终结点
EndPoint end = (EndPoint)remotepoint;
tcpsend.BeginConnect(end, new AsyncCallback(ConnectedCallback), tcpsend); //调用回调函数
connectDone.WaitOne();
return true;
}
catch
{
return false;
}
}
private void ConnectedCallback(IAsyncResult ar)
{
Socket client = (Socket)ar.AsyncState;
client.EndConnect(ar);
connect_flag = true;
connectDone.Set();
}
public void send(string data)
{
int length = data.Length;
Byte[] Bysend = new byte[length];
Bysend = System.Text.Encoding.GetEncoding("GB2312").GetBytes(data); //将字符串指定到指定Byte数组
tcpsend.BeginSend(Bysend, 0, Bysend.Length, 0, new AsyncCallback(SendCallback), tcpsend); //异步发送数据
sendDone.WaitOne();
}
private void SendCallback(IAsyncResult ar) //发送的回调函数
{
Socket client = (Socket)ar.AsyncState;
int bytesSend = client.EndSend(ar); //完成发送
sendDone.Set();
}
public void receive() //接收数据
{
//byte[] receive=new byte[1024];
tcpsend.BeginReceive(receive_buff, 0, receive_buff.Length, 0, new AsyncCallback(ReceiveCallback), tcpsend);
//sendDone.WaitOne();
}

private void ReceiveCallback(IAsyncResult ar)
{
Socket client = (Socket)ar.AsyncState; //获取句柄
int bytesread = client.EndReceive(ar);
if (bytesread > 0)
{
tcpsend.BeginReceive(receive_buff, 0, receive_buff.Length, 0, new AsyncCallback(ReceiveCallback), client);
}
else
{
readDone.Set();
}
/*
Socket client = (Socket)ar.AsyncState; //获取句柄
int bytesread = client.EndReceive(ar);
if (bytesread > 0)
{
client.BeginReceive(receive_buff, 0, receive_buff.Length, 0, new AsyncCallback(ReceiveCallback), client);
string content = Encoding.GetEncoding("GB2312").GetString(receive_buff, 0, receive_buff.Length);
richTextBox2.Text = content;
//richTextBox2.Text = Encoding.ASCII.GetString(receive_buff, 0, receive_buff.Length);
//send.tcpsend.Close();

}
else
{
readDone.Set();
}
*/
}
public Form1()
{
InitializeComponent();
}

private void btnAvaliable_Click(object sender, EventArgs e)
{
connectDone.Reset();
if (connect(textBox2.Text) == true)
{
connectDone.WaitOne();
textBox1.Text = "成功连接远程计算机";
}
else
{
textBox1.Text = "连接失败";
}
}

private void button2_Click(object sender, EventArgs e)
{
try {
// sendDone.Reset();
send(richTextBox1.Text);
// sendDone.WaitOne();
textBox1.Text = "发送成功";
readDone.Reset();
//receive();
//readDone.WaitOne();
byte[] back = new byte[1024];
int count = tcpsend.Receive((back));
richTextBox2.Text = Encoding.GetEncoding("GB2312").GetString(back, 0, count);
//tcpsend.Close();
}
catch
{
textBox1.Text = "发送异常";
}
}

private void Form1_Leave(object sender, EventArgs e)
{
tcpsend.Close();
}

private void button1_Click(object sender, EventArgs e)
{

}
}
}


服务端:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;

namespace Socket_Server_asynchronous
{
public partial class Form1 : Form
{
public int port = 8000;
public Thread threadread;
public IPEndPoint tcplisener;//将网络端点表示为IP地址和端口号
public bool listen_flag = false;
public Socket read;
public string server_ip = "127.0.0.1";
public Thread accept;//创建并控制线程

public ManualResetEvent AcceptDone = new ManualResetEvent(false); //连接的信号

public Form1()
{
InitializeComponent();
}

private void btnLink_Click(object sender, EventArgs e)
{
IPAddress ip = IPAddress.Parse(server_ip);
//用指定ip和端口号初始化
tcplisener = new IPEndPoint(ip, port);
//创建一个socket对象
read = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
read.Bind(tcplisener); //绑定
///收到客户端的连接,建立新的socket并接受信息
read.Listen(500); //开始监听
textBox1.Text = " 等待客户端连接";
accept = new Thread(new ThreadStart(Listen));
accept.Start();
// Listen();
GC.Collect();//即使垃圾回收
GC.WaitForPendingFinalizers();

}
public void Listen()
{
Thread.CurrentThread.IsBackground = true; //后台线程
try
{
while (true)
{
AcceptDone.Reset();
//Socket temp_socket = read.Accept();
read.BeginAccept(new AsyncCallback(AcceptCallback), read); //异步调用
AcceptDone.WaitOne();
}
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
}
public void AcceptCallback(IAsyncResult ar) //accpet的回调处理函数
{
AcceptDone.Set();
Socket temp_socket = (Socket)ar.AsyncState;
Socket client = temp_socket.EndAccept(ar); //获取远程的客户端
Control.CheckForIllegalCrossThreadCalls = false;
textBox1.Text = "建立连接";
IPEndPoint remotepoint = (IPEndPoint)client.RemoteEndPoint;//获取远程的端口
string remoteaddr = remotepoint.Address.ToString(); //获取远程端口的ip地址
textBox1.Text = "接收来自" + remoteaddr + "的连接";

StateObject state = new StateObject();
state.workSocket = client;
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}

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)
{
string contentstr = ""; //接收到的数据
contentstr += Encoding.GetEncoding("GB2312").GetString(state.buffer, 0, bytesRead);
richTextBox1.Text += contentstr+"\r\n";
byte[] byteData = Encoding.GetEncoding("GB2312").GetBytes("Success:" + contentstr);//回发信息
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
}
private void Send(Socket handler, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.GetEncoding("GB2312").GetBytes(data);

// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}

private void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
// Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
// int bytesSent = handler.EndSend(ar);
// Console.WriteLine("Sent {0} bytes to client.", bytesSent);
// richTextBox1.Text = "Send" + bytesSent.ToString() + "bytes to client.";
// handler.Shutdown(SocketShutdown.Both);
// handler.Close();
}

catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}

}
}

http://download.csdn.net/detail/qq_15572445/9471828
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c# socket 异步 tcp