日期:2014-05-18 浏览次数:20779 次
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.Windows.Forms; namespace tcp服务器 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } static string Msg=null; private void button1_Click(object sender, EventArgs e) { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //将该socket绑定到主机上面的某个端口 socket.Bind(new IPEndPoint(IPAddress.Any, 8888)); //启动监听,并且设置一个最大的队列长度 socket.Listen(10); richTextBox1.AppendText("Server is Lincening!"); //开始接受客户端连接请求 socket.BeginAccept(new AsyncCallback(ClientAccepted), socket); if (Msg != null) { richTextBox1.AppendText(Msg); Msg = null; } } public static void ClientAccepted(IAsyncResult ar) { var socket = ar.AsyncState as Socket; //这就是客户端的Socket实例,我们后续可以将其保存起来 var client = socket.EndAccept(ar); //接收客户端的消息(这个和在客户端实现的方式是一样的) client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), client); //准备接受下一个客户端请求 socket.BeginAccept(new AsyncCallback(ClientAccepted), socket); } static byte[] buffer = new byte[1024]; public static void ReceiveMessage(IAsyncResult ar) { try { var socket = ar.AsyncState as Socket; var length = socket.EndReceive(ar); //读取出来消息内容 var message = Encoding.Unicode.GetString(buffer, 0, length); //显示消息 //Console.WriteLine(message); string strFlog = message.Substring(0, 1); switch (int.Parse(strFlog)) { case 0: //如果首字符为0, { socket.Send(Encoding.Unicode.GetBytes("{asdasd,asd}")); } break; case 1: { string megcontent = message.Substring(1, message.Length - 1); Msg = megcontent + " 测试一在线......"+strFlog;//! } break; case 2: { string megcontent = message.Substring(1, message.Length - 1); Msg = megcontent + " 测试2在线......"+strFlog;//! } break; default: Msg = "无效信息"; break;//! } socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveMessage), socket); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }