日期:2014-05-18 浏览次数:20832 次
using System.Net; using System.Net.Sockets; 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; namespace yibutaojie { public partial class Form1 : Form { public Form1() { InitializeComponent(); } StateObject state; private void button2_Click(object sender, System.EventArgs e) { IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 2012); Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { serverSocket.Bind(localEndPoint); serverSocket.Listen(100); serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), serverSocket); } catch (Exception ee) { Console.WriteLine(ee.ToString()); } } public void AcceptCallback(IAsyncResult ar) { Socket serverSocket = (Socket)ar.AsyncState; Socket clientSocket = serverSocket.EndAccept(ar); state = new StateObject(); state.workSocket = clientSocket; Send("连接服务器成功"); clientSocket.BeginReceive(state.buffer,0,StateObject.BufferSize,0,new AsyncCallback(ReadCallback),state); } public void ReadCallback(IAsyncResult ar) { StateObject state = (StateObject)ar.AsyncState; Socket clientSocket = state.workSocket; int bytesRead = clientSocket.EndReceive(ar); if (bytesRead > 0) { String str = Encoding.Unicode.GetString(state.buffer, 0, bytesRead); textBox1.AppendText("客户端对服务器说:" + str + "\r\n"); } clientSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } private void Send(String data) { byte[] byteData=Encoding.Unicode.GetBytes(data); state.workSocket.BeginSend(byteData,0,byteData.Length,0,new AsyncCallback(SendCallback),state); } private void SendCallback(IAsyncResult ar) { try { Socket clientSocket=(Socket) ar.AsyncState; int bytesSent=clientSocket.EndSend(ar); } catch(Exception e) { Console.WriteLine(e.ToString()); } } private void button1_Click(object sender,System.EventArgs e) { textBox1.AppendText("服务器对客户端说:"+textBox2.Text+"\r\n"); Send(textBox2.Text); } private void Form1_Closing(object sender,System.ComponentModel.CancelEventArgs e) { try { state.workSocket.Shutdown(SocketShutdown.Both); state.workSocket.Close(); } catch (Exception){} } } public class StateObject { public Socket workSocket = null; public const int BufferSize = 1024; public byte[] buffer = new byte[BufferSize]; } } 提示说是“未将对象引用设置到对象的实例”,我查不出错,求高手指点。
serverSocket.BeginAccept(new AsyncCallback([color=#FF0000]AcceptCallback[/color]), serverSocket);
------解决方案--------------------