客戶端:
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(); } //發(fā)送信息 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(); } 服務(wù)端:
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); } } //獲取本機IP地址 public static IPAddress GetServerIP() { IPHostEntry ieh = Dns.GetHostEntry(Dns.GetHostName()); return ieh.AddressList[0]; } //監(jiān)聽 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() + "正在監(jiān)聽...";
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'}); richTextBox1.AppendText(msg + "\r\n"); } catch (SocketException ex) { toolStripStatusLabel1.Text += ex.ToString(); } } } |
|
來自: 賈朋亮博客 > 《socket通訊》