文件名称:网络编程 socket关键字
文件大小:59B
文件格式:TXT
更新时间:2013-05-01 13:00:39
socket
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; namespace 监听 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //第一步 ,创建一个Socket Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //第二步,绑定 //二.1,获取本机的IP地址 IPAddress[] address = Dns.GetHostAddresses(Dns.GetHostName()); //二.2,绑定 serverSocket.Bind(new IPEndPoint(address[0], 60000)); //第三步,监听 serverSocket.Listen(10); //第四步,接受 Socket clientSocket = serverSocket.Accept(); //第五步,接受数据 Byte[] buffer = new Byte[256]; clientSocket.Receive(buffer); if (buffer.Length != 0) this.listBox1.Items.Add(Encoding.UTF8.GetString(buffer)); //第六步,关闭 clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); } private void button5_Click(object sender, EventArgs e) { Socket clientSocket = new Socket(AdddressFamily.InterNetWork,SocketType.Stream,ProtocolType,Tep); IPAddress[]address = Dns.GetHostAddresses(Dns.GetHostAddresses); clientSocket.Connect(AddressFamily[1],53333); string strMsg = this.richTextBox1.Text; Byte[]buffer = Encoding.UTF8.GetBytes(strMsg); if (clientSocket !=null) { clientSocket.Send(buffer); } else MessageBox.Show("something you forgetted"); clientSocket.Shutdown(SocketShutdown.Both); } } }