您的位置:首页 > 其它

.Net socket实现简单的聊天

2009-07-27 09:47 260 查看
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.Threading;

namespace SocketServer {
public partial class Chat : Form {
public Chat() {
InitializeComponent();

this.localip.Text = GetServerIP().ToString();
}
Thread mythread;
Socket socket;

public static IPAddress GetServerIP() {
try {
IPHostEntry ieh = Dns.GetHostByName(Dns.GetHostName());
return ieh.AddressList[0];
}
catch {
throw;
}
}

public delegate void ShowResult(string msg);

public void Show(string msg) {
this.txtName.Text = msg.ToString();
}
public void ShowContents(string msg) {
this.txtContents.Text += " /r/n "+msg;
}
public void Show2(string msg) {
this.label1.Text = "ERR:"+msg.ToString();
}

private void BeginListen() {
IPAddress ServerIP = GetServerIP();
IPEndPoint iep = new IPEndPoint(ServerIP , Convert.ToInt32(this.localPort.Text));
socket = new Socket(AddressFamily.InterNetwork , SocketType.Stream , ProtocolType.Tcp);

byte[] byteMessage = new byte[1024];
//this.BeginInvoke(new ShowResult(Show) , new object[] { iep.ToString() });

socket.Bind(iep);//绑定

while (true) {
try {
socket.Listen(10);

Socket newSocket = socket.Accept();

string sTime = DateTime.Now.ToShortDateString();
//string msg = sTime + ":" + "Message From:";
int len = newSocket.Receive(byteMessage);//获取接收字符长度
string strRec = System.Text.Encoding.Default.GetString(byteMessage , 0 , len);
// msg += newSocket.RemoteEndPoint.ToString();// + Encoding.Default.GetString(byteMessage);

byte[] temp= new byte[1024];
Array.Copy(byteMessage , 0 , temp , 0,temp.Length);//根据temp的容量来取
string str = Encoding.Default.GetString(temp , 0 , temp.Length);

this.BeginInvoke(new ShowResult(ShowContents), new object[] { str });

}
catch (SocketException ex) {
this.BeginInvoke(new ShowResult(Show2) , new object[] { ex.ToString() });
}
}

}

private void button1_Click(object sender, EventArgs e)
{
if (this.localPort.Text.Trim().Equals(string.Empty)) {
MessageBox.Show("localPort 不能为空");
return;
}
try
{
mythread = new Thread(new ThreadStart(BeginListen));
mythread.Start();
this.button1.Enabled = false;
this.button2.Enabled = true;
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
}

private void button2_Click(object sender , EventArgs e) {
if (mythread.ThreadState == ThreadState.Running) {
mythread.Abort();
//socket.Shutdown(SocketShutdown.Both);
socket.Close();
this.button1.Enabled = true;
this.button2.Enabled = false;

}
}

IPAddress serverIP;
int serverPort;
Socket socketsend;

private void button3_Click(object sender, EventArgs e) {
string remotip =this.txtremotIP.Text.Trim();
int remotPort = Convert.ToInt32(this.txtremotPort.Text.Trim());

if (remotip.Equals(string.Empty) || remotPort.Equals(string.Empty)) {
MessageBox.Show("远程IP与端口都不能为空");
return;
}
int result = ConnectServer(remotip, remotPort);

if (result.Equals(0)) {
this.button3.Enabled = false;
}

}
private int ConnectServer(string sIP, int sPort) {
serverIP = IPAddress.Parse(sIP);
serverPort = sPort;

try {
IPEndPoint iep = new IPEndPoint(serverIP, serverPort);

socketsend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

socketsend.Connect(iep);

return 0;
} catch (Exception ex) {
MessageBox.Show(ex.Message.ToString());
return 1;
}
}

private void btnSend_Click(object sender, EventArgs e) {
if (socketsend != null && socketsend.Connected) {
byte[] byteMessage;

byteMessage = Encoding.Default.GetBytes(txtName.Text.Trim() + ":/r/n" + this.txtSendMsg.Text.Trim());

socketsend.Send(byteMessage);
}

}

private void Chat_FormClosing(object sender, FormClosingEventArgs e) {

if (mythread != null && mythread.ThreadState == ThreadState.Running) {
mythread.Abort();
//socket.Shutdown(SocketShutdown.Both);
socket.Close();

}
if (socketsend != null && socketsend.Connected) {
socketsend.Shutdown(SocketShutdown.Both);
socketsend.Close();
}
}

private void button4_Click(object sender, EventArgs e) {
BeginSend();
}
private void BeginSend() {

try {
string ip = this.txtremotIP.Text.Trim();
string port = this.txtremotPort.Text.Trim();

IPAddress serverIP = IPAddress.Parse(ip);
int serverPort = Convert.ToInt32(port);

IPEndPoint iep = new IPEndPoint(serverIP, serverPort);

byte[] byteMessage;

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

socket.Connect(iep);
string datestr = " "+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
string msg = txtName.Text.Trim()+ datestr +" :/r/n " + this.txtSendMsg.Text.Trim();

byteMessage = Encoding.Default.GetBytes(msg);

socket.Send(byteMessage);

socket.Shutdown(SocketShutdown.Both);

socket.Close();

ShowContents(msg);
} catch { };
}

private void button5_Click(object sender, EventArgs e) {
this.Close();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: