怎么用C#做一个C/S模式的聊天工具
3个回答
展开全部
实际是用socket方法即可实现这个功能,具体代码看如下
服务端:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/time.h>
#define BUFLEN 1024
#define PORT 6666
#define LISTNUM 20
int main()
{
int sockfd, newfd;
struct sockaddr_in s_addr, c_addr;
char buf[BUFLEN];
socklen_t len;
unsigned int port, listnum;
fd_set rfds;
struct timeval tv;
int retval,maxfd;
/*建立socket*/
if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1){
perror("socket");
exit(errno);
}else
printf("socket create success!\n");
memset(&s_addr,0,sizeof(s_addr));
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(PORT);
s_addr.sin_addr.s_addr = htons(INADDR_ANY);
/*把地址和端口帮定到套接字上*/
if((bind(sockfd, (struct sockaddr*) &s_addr,sizeof(struct sockaddr))) == -1){
perror("bind");
exit(errno);
}else
printf("bind success!\n");
/*侦听本地端口*/
if(listen(sockfd,listnum) == -1){
perror("listen");
exit(errno);
}else
printf("the server is listening!\n");
while(1){
printf("*****************聊天开始***************\n");
len = sizeof(struct sockaddr);
if((newfd = accept(sockfd,(struct sockaddr*) &c_addr, &len)) == -1){
perror("accept");
exit(errno);
}else
printf("正在与您聊天的客户端是:%s: %d\n",inet_ntoa(c_addr.sin_addr),ntohs(c_addr.sin_port));
while(1){
FD_ZERO(&rfds);
FD_SET(0, &rfds);
maxfd = 0;
FD_SET(newfd, &rfds);
/*找出文件描述符集合中最大的文件描述符*/
if(maxfd < newfd)
maxfd = newfd;
/*设置超时时间*/
tv.tv_sec = 6;
tv.tv_usec = 0;
/*等待聊天*/
retval = select(maxfd+1, &rfds, NULL, NULL, &tv);
if(retval == -1){
printf("select出错,与该客户端连接的程序将退出\n");
break;
}else if(retval == 0){
printf("waiting...\n");
continue;
}else{
/*用户输入信息了*/
if(FD_ISSET(0, &rfds)){
/******发送消息*******/
memset(buf,0,sizeof(buf));
/*fgets函数:从流中读取BUFLEN-1个字符*/
fgets(buf,BUFLEN,stdin);
/*打印发送的消息*/
//fputs(buf,stdout);
if(!strncasecmp(buf,"quit",4)){
printf("server 请求终止聊天!\n");
break;
}
len = send(newfd,buf,strlen(buf),0);
if(len > 0)
printf("\t消息发送成功:%s\n",buf);
else{
printf("消息发送失败!\n");
break;
}
}
/*客户端发来了消息*/
if(FD_ISSET(newfd, &rfds)){
/******接收消息*******/
memset(buf,0,sizeof(buf));
/*fgets函数:从流中读取BUFLEN-1个字符*/
len = recv(newfd,buf,BUFLEN,0);
if(len > 0)
printf("客户端发来的信息是:%s\n",buf);
else{
if(len < 0 )
printf("接受消息失败!\n");
else
printf("客户端退出了,聊天终止!\n");
break;
}
}
}
}
/*关闭聊天的套接字*/
close(newfd);
/*是否退出服务器*/
printf("服务器是否退出程序:y->是;n->否? ");
bzero(buf, BUFLEN);
fgets(buf,BUFLEN, stdin);
if(!strncasecmp(buf,"y",1)){
printf("server 退出!\n");
break;
}
}
/*关闭服务器的套接字*/
close(sockfd);
return 0;
}
客户端
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/time.h>
#define BUFLEN 1024
#define PORT 6666
int main(int argc, char **argv)
{
int sockfd;
struct sockaddr_in s_addr;
socklen_t len;
unsigned int port;
char buf[BUFLEN];
fd_set rfds;
struct timeval tv;
int retval, maxfd;
/*建立socket*/
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
perror("socket");
exit(errno);
}else
printf("socket create success!\n");
/*设置服务器ip*/
memset(&s_addr,0,sizeof(s_addr));
s_addr.sin_family = AF_INET;
s_addr.sin_port = htons(PORT);
if (inet_aton(argv[1], (struct in_addr *)&s_addr.sin_addr.s_addr) == 0) {
perror(argv[1]);
exit(errno);
}
/*开始连接服务器*/
if(connect(sockfd,(struct sockaddr*)&s_addr,sizeof(struct sockaddr)) == -1){
perror("connect");
exit(errno);
}else
printf("conncet success!\n");
while(1){
FD_ZERO(&rfds);
FD_SET(0, &rfds);
maxfd = 0;
FD_SET(sockfd, &rfds);
if(maxfd < sockfd)
maxfd = sockfd;
tv.tv_sec = 6;
tv.tv_usec = 0;
retval = select(maxfd+1, &rfds, NULL, NULL, &tv);
if(retval == -1){
printf("select出错,客户端程序退出\n");
break;
}else if(retval == 0){
printf("waiting...\n");
continue;
}else{
/*服务器发来了消息*/
if(FD_ISSET(sockfd,&rfds)){
/******接收消息*******/
bzero(buf,BUFLEN);
len = recv(sockfd,buf,BUFLEN,0);
if(len > 0)
printf("服务器发来的消息是:%s\n",buf);
else{
if(len < 0 )
printf("接受消息失败!\n");
else
printf("服务器退出了,聊天终止!\n");
break;
}
}
/*用户输入信息了,开始处理信息并发送*/
if(FD_ISSET(0, &rfds)){
/******发送消息*******/
bzero(buf,BUFLEN);
fgets(buf,BUFLEN,stdin);
if(!strncasecmp(buf,"quit",4)){
printf("client 请求终止聊天!\n");
break;
}
len = send(sockfd,buf,strlen(buf),0);
if(len > 0)
printf("\t消息发送成功:%s\n",buf);
else{
printf("消息发送失败!\n");
break;
}
}
}
}
/*关闭连接*/
close(sockfd);
return 0;
}
客户端我们可以放到任何一台机子上,只要保证都能在同一个局域网下,连到自己的IP地址就行。开启服务端后,在开启客户端,就可以聊天了:
服务端:
waiting...
waiting...
waiting...
nihal
消息发送成功:nihal
客户端发来的信息是:zhuzhu
hehe
消息发送成功:hehe
客户端发来的信息是:haha
客户端退出了,聊天终止!
服务器是否退出程序:y->是;n->否? y
server端退出。
客户端
waiting...
waiting...
waiting...
服务器发来的消息是:nihal
zhuzhu
消息发送成功:zhuzhu
服务器发来的消息是:hehe
haha
消息发送成功:haha
展开全部
TCP UDP 都可以。如果多人的话 必须有个服务器 点对点的话 客户端即服务器。
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.Sockets;
using System.Net;
using System.Threading;
namespace CHEAT
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
EndPoint ep;
string receiveData;
bool _star = false;
private void AcceptMessage()
{
//d定义socket对象
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 8899);
socket.Bind(iep);
ep = (EndPoint)iep;
try
{
while (!_star)
{
byte[] bytes = new byte[1024];
socket.ReceiveFrom(bytes, ref ep);
receiveData = System.Text.Encoding.Unicode.GetString(bytes);
receiveData = receiveData.TrimEnd('\u0000');
Thread th = new Thread(new ThreadStart(Acc));
th.Start();
}
}
catch (Exception)
{
socket.Close();
}
}
private delegate void SetTextCallbakc();
private void Acc() //多线程
{
SetTextCallbakc stcb = new SetTextCallbakc(callbakc);
Invoke(stcb); //代理
}
private void callbakc() //弹窗参数
{
string time = DateTime.Now.ToString();
string message = "来自" + ep.ToString() + "的消息 "+time + "\r\n";
textBox1.Text +=message+ receiveData +"\r\n";
}
private void button1_Click(object sender, EventArgs e)
{
//只能用UDP协议发送广播,所以ProtocolType设置为UDP
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//让其自动提供子网中的IP地址
IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 8899);
//设置broadcast值为1,允许套接字发送广播信息
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
//将发送内容转换为字节数组
byte[] bytes = System.Text.Encoding.Unicode.GetBytes(this.textBox2.Text);
//向子网发送信息
socket.SendTo(bytes, iep);
socket.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox2.Focus();
Thread th = new Thread(new ThreadStart(AcceptMessage));
th.Start();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
}
}
这是一个基于udp的 纯手敲 望采纳
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.Sockets;
using System.Net;
using System.Threading;
namespace CHEAT
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
EndPoint ep;
string receiveData;
bool _star = false;
private void AcceptMessage()
{
//d定义socket对象
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 8899);
socket.Bind(iep);
ep = (EndPoint)iep;
try
{
while (!_star)
{
byte[] bytes = new byte[1024];
socket.ReceiveFrom(bytes, ref ep);
receiveData = System.Text.Encoding.Unicode.GetString(bytes);
receiveData = receiveData.TrimEnd('\u0000');
Thread th = new Thread(new ThreadStart(Acc));
th.Start();
}
}
catch (Exception)
{
socket.Close();
}
}
private delegate void SetTextCallbakc();
private void Acc() //多线程
{
SetTextCallbakc stcb = new SetTextCallbakc(callbakc);
Invoke(stcb); //代理
}
private void callbakc() //弹窗参数
{
string time = DateTime.Now.ToString();
string message = "来自" + ep.ToString() + "的消息 "+time + "\r\n";
textBox1.Text +=message+ receiveData +"\r\n";
}
private void button1_Click(object sender, EventArgs e)
{
//只能用UDP协议发送广播,所以ProtocolType设置为UDP
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//让其自动提供子网中的IP地址
IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 8899);
//设置broadcast值为1,允许套接字发送广播信息
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
//将发送内容转换为字节数组
byte[] bytes = System.Text.Encoding.Unicode.GetBytes(this.textBox2.Text);
//向子网发送信息
socket.SendTo(bytes, iep);
socket.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
textBox2.Focus();
Thread th = new Thread(new ThreadStart(AcceptMessage));
th.Start();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
}
}
这是一个基于udp的 纯手敲 望采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
核心技术主要有两个:
客户端、服务器端通信;显示输出。
如果你写过局域网的聊天工具,我想它本来就是C/S模式的。
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询