.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();
}
}
}
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();
}
}
}
相关文章推荐
- java Socket简单聊天实现 —— 实现服务器端向客户端广播内容
- 用UDP实现简单的聊天功能
- socket 编程 TCP 实现简单聊天功能
- 记websocket(windows系统下nodejs,node-websocket-server实现简单聊天)
- Android基于socket实现的简单C/S聊天通信功能
- HTML5基于Tomcat 7.0实现WebSocket连接并实现简单的实时聊天
- pyqt5实现简单的 p2p聊天
- Tcp 实现简单的聊天
- python实现简单聊天程序
- JAVA 多线程实现简单UDP一对一聊天
- PHP+swoole实现简单多人在线聊天群发
- android实验三 简单聊天记录的设计与实现
- Unity3D 实现简单的语音聊天 [iOS版本]
- Java一步一脚印—通过简单的TCP网络编程实现局域网的聊天对话
- 使用Express + Socket.io + MongoDB实现简单的聊天
- 使用Socket实现简单聊天
- 关于java通信的一个简单聊天系统的实现
- java多线程以及java网络编程实现简单的聊天系统
- qt 实现简单聊天(一个服务器和多个客服端)
- Java swing实现简单的C/S聊天及文件传输系统