* 基于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 <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <pthread.h>
#define MAXLINE 100
void *threadsend(void *vargp)
void *threadrecv(void *vargp)
int main()
{
int *clientfdp
clientfdp = (int *)malloc(sizeof(int))
*clientfdp = socket(AF_INET,SOCK_STREAM,0)
struct sockaddr_in serveraddr
struct hostent *hp
bzero((char *)&serveraddr,sizeof(serveraddr))
serveraddr.sin_family = AF_INET
serveraddr.sin_port = htons(15636)
serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1")
if(connect(*clientfdp,(struct sockaddr *)&serveraddr,sizeof(serveraddr)) <0){
printf("connect error\n")
exit(1)
}
pthread_t tid1,tid2
printf("connected\n")
while(1){
pthread_create(&tid1,NULL,threadsend,clientfdp)
pthread_create(&tid2,NULL,threadrecv,clientfdp)
}
return EXIT_SUCCESS
}
void *threadsend(void * vargp)
{
//pthread_t tid2
int connfd = *((int *)vargp)
int idata
char temp[100]
while(1){
//printf("me: \n ")
fgets(temp,100,stdin)
send(connfd,temp,100,0)
printf(" 友链 client send OK\n")
}
printf("client send\n")
return NULL
}
void *threadrecv(void *vargp)
{
char temp[100]
int connfd = *((int *)vargp)
while(1){
int idata = 0
idata = recv(connfd,temp,100,0)
if(idata >0){
printf("server :\n%s\n",temp)
}
}
return NULL
}
扩展资料:注意事项
linux下编译多线程代码时,shell提示找键告蠢不到 pthread_create函数,原因是 pthread.h不是linux系统默认加载的库文件,应该使用类似如下gcc命令进行编译稿陪:
gcc echoserver.c -lpthread -o echoserver
只要注意 -lpthread参数就可以了。
用c写可是一个浩大的工程,为什么不用c#呢?你郑逗的要求基本就是一个成吵芹型的软件了!如果是学习的话你可以去网上花百八十买套专门写聊天软件的课程。对了没有C的,java c#倒是都有升丛毕。欢迎分享,转载请注明来源:内存溢出
评论列表(0条)