* 基于UDP协议的聊天程序
*
*2007.9.18
* */
//导入包
import java.awt.*
import java.awt.event.*
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import javax.swing.*
import java.net.*
public class Chat extends JFrame implements ActionListener
{
//广播地址或者对方的地址
public static final String sendIP = "172.18.8.255"
//发送端口9527
public static final int sendPort = 9527
JPanel p = new JPanel()
List lst = new List() //消息显示
JTextField txtIP = new JTextField(18)//填写IP地址
JTextField txtMSG = new JTextField(20)//填写发送消息
JLabel lblIP = new JLabel("IP地址:")
JLabel lblMSG = new JLabel("消息:")
JButton btnSend = new JButton("发送")
byte [] buf
//定义DatagramSocket的对象必须进行异常处理
//发送和接收数据报包的套接字
DatagramSocket ds = null
//=============构造函数=====================
public Chat()
{
CreateInterFace()
//注册消息框监听器
txtMSG.addActionListener(this)
btnSend.addActionListener(this)
try
{
//端口:9527
ds =new DatagramSocket(sendPort)
}
catch(Exception ex)
{
ex.printStackTrace()
}
//============接受消息============
//匿名类
new Thread(new Runnable()
{
public void run()
{
byte buf[] = new byte[1024]
//表示接受数据报包
while(true)
{
try
{
DatagramPacket dp = new DatagramPacket(buf,1024,InetAddress.getByName(txtIP.getText()),sendPort)
ds.receive(dp)
lst.add("【消息来自】◆" + dp.getAddress().getHostAddress() + "◆"+"【说】:" + new String (buf,0,dp.getLength()) /*+ dp.getPort()*/,0)
}
catch(Exception e)
{
if(ds.isClosed())
{
e.printStackTrace()
}
}
}
}
}).start()
//关闭窗体事件
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.out.println("test")
int n=JOptionPane.showConfirmDialog(null,"是否要退出?","退出",JOptionPane.YES_NO_OPTION)
if(n==JOptionPane.YES_OPTION)
{
dispose()
System.exit(0)
ds.close()//关闭ds对象//关闭数据报套接字
}
}
})
}
//界面设计布局
public void CreateInterFace()
{
this.add(lst,BorderLayout.CENTER)
this.add(p,BorderLayout.SOUTH)
p.add(lblIP)
p.add(txtIP)
p.add(lblMSG)
p.add(txtMSG)
p.add(btnSend)
txtIP.setText(sendIP)
//背景颜色
lst.setBackground(Color.yellow)
//JAVA默认风格
this.setUndecorated(true)
this.getRootPane().setWindowDecorationStyle(JRootPane.FRAME)
this.setSize(600,500)
this.setTitle("〓聊天室〓")
this.setResizable(false)//不能改变窗体大小
this.setLocationRelativeTo(null)//窗体居中
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
this.setVisible(true)
txtMSG.requestFocus()//消息框得到焦点
}
//===============================Main函数===============================
public static void main(String[]args)
{
new Chat()
}
//================================发送消息===============================
//消息框回车发送消息事件
public void actionPerformed(ActionEvent e)
{
//得到文本内容
buf = txtMSG.getText().getBytes()
//判断消息框是否为空
if (txtMSG.getText().length()==0)
{
JOptionPane.showMessageDialog(null,"发送消息不能为空","提示",JOptionPane.WARNING_MESSAGE)
}
else{
try
{
InetAddress address = InetAddress.getByName(sendIP)
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort)
ds.send(dp)
}
catch(Exception ex)
{
ex.printStackTrace()
}
}
txtMSG.setText("")//清空消息框
//点发送按钮发送消息事件
if(e.getSource()==btnSend)
{
buf = txtMSG.getText().getBytes()
try
{
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort)
}
catch(Exception ex)
{
ex.printStackTrace()
}
txtMSG.setText("")//清空消息框
txtMSG.requestFocus()
}
}
}
#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>
#defineBUFLEN1024
#definePORT6666
#defineLISTNUM20
intmain()
{
intsockfd,newfd
structsockaddr_ins_addr,c_addr
charbuf[BUFLEN]
socklen_tlen
unsignedintport,listnum
fd_setrfds
structtimevaltv
intretval,maxfd
/*建立socket*/
if((sockfd=socket(PF_INET,SOCK_STREAM,0))==-1){
perror("socket")
exit(errno)
}else
printf("socketcreatesuccess!\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,(structsockaddr*)&s_addr,sizeof(structsockaddr)))==-1){
perror("bind")
exit(errno)
}else
printf("bindsuccess!\n")
/*侦听本地端口*/
if(listen(sockfd,listnum)==-1){
perror("listen")
exit(errno)
}else
printf("theserverislistening!\n")
while(1){
printf("*****************聊天开始***************\n")
len=sizeof(structsockaddr)
if((newfd=accept(sockfd,(structsockaddr*)&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
}elseif(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)
return0
}
扩展资料
C语言编写一个简单的ATM系统
#include<stdio.h>
intchoice
intshow_menu()
doubleget_money()
voiddeposit(double)
voidwithdraw(double)
doubleaccount=0.0
intmain(intargc,constchar*argv[])
{
system("COLOR5f")
show_menu()
doubletemp
while(choice!=0)
{
system("cls")
switch(choice)
{
case1:
printf("您的当前余额为:%.2f\n",get_money())
break
case2:
printf("请输入您的存款金额:\n")
scanf("%lf",&temp)
deposit(temp)
printf("您的当前余额为:%.2f\n",get_money())
break
case3:
printf("您的当前余额为:%.2f\n",get_money())
printf("请输入您的取款金额:\n")
scanf("%lf",&temp)
withdraw(temp)
printf("您的当前余额为:%.2f\n",get_money())
break
default:
break
}
getchar()
choice=show_menu()
}
printf("欢迎您下次再来中国银行为您提供的服务,再见!\n")
return0
}
intshow_menu()
{
printf("*****欢迎使用中国银行行为为您提供的服务******\n")
printf("\n1.查询账户余额2.存款3.取款0.退出\n")
printf("\n请选择服务种类:")
scanf("%d",&choice)
returnchoice
}
doubleget_money()
{
returnaccount
}
voiddeposit(doublemoney)
{
account=account+money
}
voidwithdraw(doublemoney)
{
if(account<money)
printf("抱歉,余额不足,不能取%.2f这么多钱!\n",money)
else
account=account-money
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)