您的位置:首页 > 编程语言 > C#

C# SOCKET编写的简单聊天通信程序(客户端+服务端)

2013-07-06 01:51 846 查看
初学C#的SOCKET编程,照着网上的代码写下来,程序总是有问题,经过自己长时间的调试,完成程序,以下是原码,有需要可以参考一下,还不完善,欢迎大家批评指正。
(这里的代码没更新,附件重新上传更新,在另一个线程中使用委托来修改控件的属性,发送广播功能还有问题,稍修更新修正。)
环境:VS2008 .NET3.5
网上给出的程序都是控制台程序,我这个是WINFORM程序。有详细的说明,以服务端程序。

服务端:
需要增加的命名空间:

using System.Threading;
using System.Net;
using System.Net.Sockets;


以下是具体实现。

C# code复制代码

namespace TCPServer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

}
public bool btnstatu = true;    //开始停止服务按钮状态
public Thread myThread;             //声明一个线程实例
public Socket newsock;                //声明一个Socket实例
public Socket Client;
public IPEndPoint localEP;
public int localPort;
public bool m_Listening;
//用来设置服务端监听的端口号
public int setPort
{
get { return localPort; }
set { localPort = value; }
}

//用来往richtextbox框中显示消息
public void showClientMsg(string msg)
{
showClientMsg(msg+"\r\n");
}
//监听函数
public void Listen()
{     //设置端口
setPort=int.Parse(serverport.Text.Trim());
//初始化SOCKET实例
newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//初始化终结点实例
localEP=new IPEndPoint(IPAddress.Any,setPort);
try
{
//绑定
newsock.Bind(localEP);
//监听
newsock.Listen(10);
//用于设置按钮状态
m_Listening = true;
//开始接受连接,异步。
newsock.BeginAccept(new AsyncCallback(OnConnectRequest), newsock);
}
catch (Exception ex)
{
showClientMsg(ex.Message);
}

}
//当有客户端连接时的处理
public void OnConnectRequest(IAsyncResult ar)
{
//初始化一个SOCKET,用于其它客户端的连接
Socket server1 = (Socket)ar.AsyncState;
Client = server1.EndAccept(ar);
//将要发送给连接上来的客户端的提示字符串
string strDateLine = "Welcome here";
Byte[] byteDateLine = System.Text.Encoding.ASCII.GetBytes(strDateLine);
//将提示信息发送给客户端
Client.Send(byteDateLine, byteDateLine.Length, 0);
//等待新的客户端连接
server1.BeginAccept(new AsyncCallback(OnConnectRequest), server1);
while (true)
{
int recv = Client.Receive(byteDateLine);
string stringdata = Encoding.ASCII.GetString(byteDateLine, 0, recv);
DateTimeOffset now = DateTimeOffset.Now;
//获取客户端的IP和端口
string ip = Client.RemoteEndPoint.ToString();
if (stringdata == "STOP")
{
//当客户端终止连接时
showinfo.AppendText(ip+"已从服务器断开");
break;
}
//显示客户端发送过来的信息
showinfo.AppendText(ip + "    " + now.ToString("G") + "     " + stringdata + "\r\n");
}

}
//开始停止服务按钮
private void startService_Click(object sender, EventArgs e)
{
//新建一个委托线程
ThreadStart myThreadDelegate = new ThreadStart(Listen);
//实例化新线程
myThread = new Thread(myThreadDelegate);

if (btnstatu)
{

myThread.Start();
statuBar.Text = "服务已启动,等待客户端连接";
btnstatu = false;
startService.Text = "停止服务";
}
else
{
//停止服务(功能还有问题,无法停止)
m_Listening = false;
newsock.Close();
myThread.Abort();
showClientMsg("服务器停止服务");
btnstatu = true;
startService.Text = "开始服务";
statuBar.Text = "服务已停止";
m_Listening = false;
}

}
//窗口关闭时中止线程。
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (myThread != null)
{
myThread.Abort();
}
}
}
}


客户端:

C# code复制代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace TCPClient
{
public partial class Form1 : Form
{
public Socket newclient;
public bool Connected;
public Thread myThread;
public delegate void MyInvoke(string str);
public Form1()
{
InitializeComponent();

}
public void Connect()
{
byte[] data = new byte[1024];
newclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
string ipadd = serverIP.Text.Trim();
int port = Convert.ToInt32(serverPort.Text.Trim());
IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipadd), port);
try
{
newclient.Connect(ie);
connect.Enabled = false;
Connected = true;

}
catch(SocketException e)
{
MessageBox.Show("连接服务器失败    "+e.Message);
return;
}
ThreadStart myThreaddelegate = new ThreadStart(ReceiveMsg);
myThread = new Thread(myThreaddelegate);
myThread.Start();

}
public void ReceiveMsg()
{
while (true)
{
byte[] data = new byte[1024];
int recv = newclient.Receive(data);
string stringdata = Encoding.UTF8.GetString(data, 0, recv);
showMsg(stringdata + "\r\n");
//receiveMsg.AppendText(stringdata + "\r\n");
}
}
public void showMsg(string msg)
{
{
//在线程里以安全方式调用控件
if (receiveMsg.InvokeRequired)
{
MyInvoke _myinvoke = new MyInvoke(showMsg);
receiveMsg.Invoke(_myinvoke, new object[] { msg });
}
else
{
receiveMsg.AppendText(msg);
}
}
}

private void SendMsg_Click(object sender, EventArgs e)
{
int m_length = mymessage.Text.Length;
byte[] data=new byte[m_length];
data = Encoding.UTF8.GetBytes(mymessage.Text);
int i = newclient.Send(data);
showMsg("我说:" + mymessage.Text + "\r\n");
//receiveMsg.AppendText("我说:"+mymessage.Text + "\r\n");
mymessage.Text = "";
//newclient.Shutdown(SocketShutdown.Both);
}

private void connect_Click(object sender, EventArgs e)
{
Connect();
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: