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];
}
}
提示说是“未将对象引用设置到对象的实例”,我查不出错,求高手指点。
解决方案 »
- 工具栏toolstriplabel鼠标移动到上面的背景色怎么改?
- 求一条正则表达式,内详
- 存储过程中怎样触发某个应用程序
- 如何从 sp_oaMethod 中得到调用方法的返回值?
- Dundas Chart 问题
- 请教各位大哥: 为啥设定Timer定时器时不产生一个新的线程,而要到执行Callback时才产生一个线程呢?
- 星星高手关注下:Winform程序软件国际化多语言动态切换后显示异常,有图进入查看
- iframe高度自适应问题
- 有没有关于C#语言的数据结构与算法书籍呀?
- 用InstallUtil.exe无法安装Window Service? 老是报错,如何解决?
- C#客户端发帖功能,怎样动态添加panel
- 怎么让子线程结束后继续主线程?
是不是
public void AcceptCallback(IAsyncResult ar)
这个东西?