日期:2014-05-20 浏览次数:21466 次
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Windows.Forms; //添加引用 using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; namespace SocketServer { public partial class Form1 : Form { Thread mythread;//创建线程 Socket socket; int port = 8000;//定义侦听端口号 public Form1()//服务器端 { InitializeComponent(); } //获取本机IP地址 public static IPAddress GetServerIP() { IPHostEntry ieh = Dns.GetHostEntry(Dns.GetHostName()); return ieh.AddressList[0]; } //监听 private void BeginListen() { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ServerIp = GetServerIP(); IPEndPoint iep = new IPEndPoint(ServerIp, port); socket.Bind(iep); toolStripStatusLabel1.Text = iep.ToString() + "正在监听..."; byte[] byteMessage = new byte[100]; while (true) { try { socket.Listen(5); Socket newSocket = socket.Accept(); newSocket.Receive(byteMessage); string sTime = DateTime.Now.ToShortTimeString(); string msg = sTime + "-" + "信息来自:"; msg += newSocket.RemoteEndPoint.ToString() +" "+ Encoding.Default.GetString(byteMessage).Trim(new char[] {'\0'}); [color=#FF0000]this.richTextBox1.AppendText(msg + "\r\n");[/color] } catch (SocketException ex) { toolStripStatusLabel1.Text += ex.ToString(); } } } private void btn_Listen_Click(object sender, EventArgs e) { try { mythread = new Thread(new ThreadStart(BeginListen)); mythread.Start(); } catch (System.Exception er) { MessageBox.Show(er.Message, "完成", MessageBoxButtons.OK, MessageBoxIcon.Stop); } } } }
using System; using System.Windows.Forms; //添加引用 using System.Net; using System.Net.Sockets; using System.Text; namespace SocketClient { public partial class Form1 : Form { public Form1()//客户端 { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { //得到本机地址 IPHostEntry ieh = Dns.GetHostEntry(Dns.GetHostName()); txtIP.Text = ieh.AddressList[0].ToString(); } private void btn_Send_Click(object sender, EventArgs e) { BeginSend(); } //发送信息 private void BeginSend() { string ip = txtIP.Text; string port = txtPort.Text; string msg = txtMsg.Text.Trim(); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress serverIp = IPAddress.Parse(ip); int serverPort = Convert.ToInt32(port); IPEndPoint iep = new IPEndPoint(serverIp, serverPort); socket.Connect(iep); byte[] byteMessage; byteMessage = Encoding.ASCII.GetBytes(msg); socket.Send(byteMessage); socket.Shutdown(SocketShutdown.Both); socket.Close(); } } }