服務器:
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.Sockets;
using System.Net;
using System.Reflection;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace msgServer
{
public partial class frmServer : Form
{
private Socket socket;
private IPAddress myIP;
private IPEndPoint endPoint;
private int point;
private Socket clientSocket;
private Assembly ass = null;
private System.IO.Stream stream = null;
private System.Media.SoundPlayer pl;
private string txt;
private byte[] bs = new byte[512];
public frmServer()
{
InitializeComponent();
ass = Assembly.GetExecutingAssembly();
stream = ass.GetManifestResourceStream("msgServer.msg.wav");
pl = new System.Media.SoundPlayer(stream);
}
//字體選擇
private void btnFont_Click(object sender, EventArgs e)
{
FontDialog font = new FontDialog();
font.ShowEffects = true;
font.ShowColor = true;
font.MinSize = 12;
font.Font = new Font("楷體_GB2312", 18, FontStyle.Bold);
font.Color = Color.Blue;
if (font.ShowDialog() == DialogResult.OK)
{
rtxtSend.Font = font.Font;
rtxtSend.ForeColor = font.Color;
}
}
//開始監聽
private void btnStart_Click(object sender, EventArgs e)
{
System.Threading.Thread th1 = new System.Threading.Thread(ToConnect);
th1.Start();
}
//去連接
private void ToConnect()
{
try
{
myIP = IPAddress.Parse(txtIP.Text.Trim());//IP
point = Convert.ToInt32(txtPoint.Text.Trim());//Point
endPoint = new IPEndPoint(myIP, point); //終端
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(endPoint);//綁定
socket.Listen(3); //最多3人同時連接
lblStatus.Text = "服務器已經運行...";
clientSocket = socket.Accept();//等待接受
//連接上時
if (clientSocket.Connected)
{
lblStatus.Text = "已經建立連接.";
while (true)
{
try
{
clientSocket.Receive(bs, bs.Length, 0);
pl.Play();
rtxtMsg.AppendText(System.Text.Encoding.Unicode.GetString(bs));
}
catch { lblStatus.Text = "連接已經斷開."; }
}
}
}
catch { txtIP.Focus(); txtIP.SelectAll(); MessageBox.Show("IP error OR Point error"); }
}
//停止監聽
private void btnStop_Click(object sender, EventArgs e)
{
try
{
socket.Close(3);
lblStatus.Text = "監聽已經停止.";
}
catch
{
lblStatus.Text = "目前未建立連接.";
}
}
private void frmServer_KeyPress(object sender, KeyPressEventArgs e)
{
}
private void frmServer_KeyDown(object sender, KeyEventArgs e)
{
if ((e.Control && e.KeyCode == Keys.Enter) || (e.Alt && e.KeyCode == Keys.S))
{
btnSend.PerformClick();//單擊發送
}
}
//發送消息
private void btnSend_Click(object sender, EventArgs e)
{
if (rtxtSend.Text.Trim() == "")
return;
else if (rtxtSend.Text.Trim().ToLower() == "clear()")
{
rtxtMsg.Clear();
rtxtSend.Text = "";
return;
}
else if (Regex.IsMatch(rtxtSend.Text.Trim().ToLower(), @"^[zoom(]+[\d]+[)]$"))
{
string str = rtxtSend.Text.ToLower();
int size = Convert.ToInt32(str.Substring(str.LastIndexOf('(') + 1,
str.IndexOf(')') - str.LastIndexOf('(') - 1));
rtxtMsg.Font = new Font("宋體", size,FontStyle.Bold);
return;
}
else if (Regex.IsMatch(rtxtSend.Text.Trim().ToLower(), @"^[down(]+[\d]+[)]$"))
{
string str = rtxtSend.Text.ToLower();
string size = str.Substring(str.LastIndexOf('(') + 1,str.IndexOf(')') - str.LastIndexOf('(') - 1);
if (Convert.ToInt32(size) > rtxtMsg.Text.Length)
return;
}
else if (Regex.IsMatch(rtxtSend.Text.Trim().ToLower(), @"^[up(]+[\d]+[)]$"))
{
string str = rtxtSend.Text.ToLower();
string size = str.Substring(str.LastIndexOf('(') + 1,str.IndexOf(')') - str.LastIndexOf('(') - 1);
}
else if (rtxtSend.Text.Trim().ToLower() == "exit(0)")
{
this.Close();
return;
}
try
{
byte[] bs = new byte[512];
string user = null;
if (txtUser.Text.Trim() == "在此輸入妳的名字" || txtUser.Text.Trim() == "")
{
user = "我";
bs = Encoding.Unicode.GetBytes(string.Format("對方說:({0})\r\n{1}\r\n",DateTime.Now.ToString(), rtxtSend.Text.Trim()));
}
else
{
bs = Encoding.Unicode.GetBytes(string.Format("{0}說:({1})\r\n{2}\r\n", txtUser.Text.Trim(),DateTime.Now.ToString(), rtxtSend.Text.Trim()));
user = txtUser.Text.Trim();
}
clientSocket.Send(bs, bs.Length, 0);//發送
txt = string.Format("{0}說:({1})\r\n{2}\r\n", user, DateTime.Now.ToString(),rtxtSend.Text.Trim());
int tempLen = rtxtMsg.Text.Length;
rtxtMsg.AppendText(txt);
rtxtMsg.Select(tempLen, txt.Length);
rtxtMsg.SelectionFont = new Font("宋體", 10);
rtxtMsg.SelectionColor = Color.Red;
rtxtSend.Clear();
}
catch { MessageBox.Show("未建立連接,無法發送數據!"); }
}
//關閉Socket
private void frmServer_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
//關閉連接
socket.Close(3);
}
catch (Exception) { }
finally
{
foreach (Process p in Process.GetProcesses())
{
if (p.ProcessName == Application.ProductName)
p.Kill();
}
}
}
private void frmServer_Load(object sender, EventArgs e)
{
foreach (Process p in Process.GetProcesses())
{
if (p.ProcessName == Application.ProductName)//已經啟動
{
if (p.Id != Process.GetCurrentProcess().Id)//不是當前進程
{
p.Kill();
}
}
}
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
this.TopMost = checkBox1.Checked;
}
}
}
客戶端:
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;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace smgClient
{
public partial class frmClient : Form
{
private IPAddress IP;//ip
private EndPoint endpoint;//point
private Socket socket;//socket
private System.IO.Stream stream = null;
private System.Reflection.Assembly ass = null;
private System.Media.SoundPlayer pl = null;
private string txt;
private byte[] bs = new byte[512];
public frmClient()
{
InitializeComponent();
ass = System.Reflection.Assembly.GetExecutingAssembly();
stream = ass.GetManifestResourceStream("smgClient.msg.wav");
pl = new System.Media.SoundPlayer(stream);
}
//請求連接
private void btnRequestConnect_Click(object sender, EventArgs e)
{
System.Threading.Thread th = new System.Threading.Thread(this.ToConnect);
th.Start();
}
//連接服務器
private void ToConnect()
{
try
{
IP = IPAddress.Parse(txtIP.Text.Trim());
int point = Convert.ToInt32(txtPoint.Text.Trim());
endpoint = new IPEndPoint(IP, point);
//建立Socket
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//建立連接
socket.Connect(endpoint);
//連接成功
lblStatus.Text = "連接成功.";
while (true)
{
socket.Receive(bs, bs.Length, 0);
pl.Play();
rtxtMsg.AppendText(System.Text.Encoding.Unicode.GetString(bs));
}
}
catch (FormatException)
{ MessageBox.Show("IP error OR Point error"); }
catch (ArgumentNullException)
{ MessageBox.Show("IP error OR Point error"); }
catch (Exception)
{
lblStatus.Text = "連接失敗,原因: 服務器已停止.";
}
}
//字體
private void btnFont_Click(object sender, EventArgs e)
{
FontDialog font = new FontDialog();
font.ShowEffects = true;
font.ShowColor = true;
font.MinSize = 12;
font.Font = new Font("楷體_GB2312", 18, FontStyle.Bold);
font.Color = Color.Blue;
if (font.ShowDialog() == DialogResult.OK)
{
rtxtSend.Font = font.Font;
rtxtSend.ForeColor = font.Color;
}
}
//關閉連接
private void btnCloseConnect_Click(object sender, EventArgs e)
{
try
{
socket.Close();
lblStatus.Text = "連接已經關閉.";
}
catch
{
lblStatus.Text = "目前未建立連接.";
}
}
//發送消息
private void btnSend_Click(object sender, EventArgs e)
{
if (rtxtSend.Text.Trim() == "")
return;
else if (rtxtSend.Text.Trim().ToLower() == "clear()")
{
rtxtMsg.Clear();
rtxtSend.Text = "";
return;
}
else if (Regex.IsMatch(rtxtSend.Text.Trim().ToLower(), @"^[zoom(]+[\d]+[)]$"))
{
string str = rtxtSend.Text.ToLower();
int size = Convert.ToInt32(str.Substring(str.LastIndexOf('(') + 1,
str.IndexOf(')') - str.LastIndexOf('(') - 1));
rtxtMsg.Font = new Font("宋體", size, FontStyle.Bold);
return;
}
else if (Regex.IsMatch(rtxtSend.Text.Trim().ToLower(), @"^[down(]+[\d]+[)]$"))
{
string str = rtxtSend.Text.ToLower();
string size = str.Substring(str.LastIndexOf('(') + 1, str.IndexOf(')') - str.LastIndexOf('(') - 1);
if (Convert.ToInt32(size) > rtxtMsg.Text.Length)
return;
}
else if (Regex.IsMatch(rtxtSend.Text.Trim().ToLower(), @"^[up(]+[\d]+[)]$"))
{
string str = rtxtSend.Text.ToLower();
string size = str.Substring(str.LastIndexOf('(') + 1, str.IndexOf(')') - str.LastIndexOf('(') - 1);
}
else if (rtxtSend.Text.Trim().ToLower() == "exit(0)")
{
this.Close();
return;
}
try
{
byte[] bs = new byte[512];
string user = null;
if (txtUser.Text.Trim() == "在此輸入妳的名字" || txtUser.Text.Trim() == "")
{
user = "我";
bs = Encoding.Unicode.GetBytes(string.Format("對方說:({0})\r\n{1}\r\n", DateTime.Now.ToString(),rtxtSend.Text.Trim()));
}
else
{
bs = Encoding.Unicode.GetBytes(string.Format("{0}說:({1})\r\n{2}\r\n", txtUser.Text.Trim(),DateTime.Now.ToString(),rtxtSend.Text.Trim()));
user = txtUser.Text.Trim();
}
socket.Send(bs, bs.Length, 0);//發送
txt = string.Format("{0}說:({1})\r\n{2}\r\n", user, DateTime.Now.ToString(), rtxtSend.Text.Trim());
int tempLen = rtxtMsg.Text.Length;
rtxtMsg.AppendText(txt);
rtxtMsg.Select(tempLen, txt.Length);
rtxtMsg.SelectionFont = new Font("宋體", 10);
rtxtMsg.SelectionColor = Color.Red;
rtxtSend.Clear();
}
catch(Exception ex)
{ MessageBox.Show("連接尚未建立!無法發送數據!" + ex.Message); }
}
//避開打開多個
private void frmClient_Load(object sender, EventArgs e)
{
foreach (Process p in Process.GetProcesses())
{
if (p.ProcessName == Application.ProductName)//有進程
{
if (p.Id != Process.GetCurrentProcess().Id)//不是當前進程
{
p.Kill();
}
}
}
}
private void frmClient_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
socket.Close();
}
catch(Exception) { }
finally
{
foreach (Process p in Process.GetProcesses())
{
if (p.ProcessName == Application.ProductName)
p.Kill();
}
}
}
private void frmClient_KeyDown(object sender, KeyEventArgs e)
{
if ((e.Control && e.KeyCode == Keys.Enter) || (e.Alt && e.KeyCode == Keys.S))
{
btnSend.PerformClick();
}
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
this.TopMost = checkBox1.Checked;
}
}
}