怎样用java编写一个即时聊天程序呢?下面yjbys小编就为大家分享最新的`java即时聊天程序编写方法,一起来看看吧!
import .*;
import t.*;
import .*;
/**
* Sample application using Frame.
*
* @author
* @version 1.00 07/06/13
*/
public class Chatp2pFrame extends Frame {
List dataList=new List(26);
TextField Tfip=new TextField(18);
TextField Tfdata=new TextField(19);
Label Lip=new Label("输入对方的IP地址:");
Label Ldata=new Label("输入聊天的内容:");
DatagramSocket socket=null;
/**
* The constructor.
*/
public Chatp2pFrame() {
try
{
socket=new DatagramSocket(5000);
}
catch(Exception e)
{
tStackTrace();
}
ize(150,15);
ize(150,15);
ocusable(true);
oreground();
oreground();
oreground(k);
(dataList,"North");
Panel p1=new Panel();
Panel p2=new Panel();
ayout(new BorderLayout());
ayout(new BorderLayout());
(p1,"Center");
(p2,"South");
(Lip,"West");
(Ldata,"East");
(Tfip,"West");
(Tfdata,"East");
new Thread(new Runnable()
{
public void run()
{
byte[] buf=new byte[1024];
DatagramPacket packet=new DatagramPacket(buf,1024);
while(true)
{
try
{
ive(packet);
(new String(buf,0,ength())+" FROM "+ddress()ostAddress()+":"+ort(),0);
}
catch(Exception e)
{
if(!osed())
{
tStackTrace();
}
}
}
}
}
)t();
ctionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
byte[] buf=new byte[1024];
buf=ext()ytes();
DatagramPacket packet=new DatagramPacket(buf,th,
yName(ext()),5000);
(packet);
(new String(buf,0,ength())+" TO "+ddress()ostAddress()+":"+ort(),0);
}
catch(Exception x)
{
tStackTrace();
}
ext("");
}
}
);
MenuBar menuBar = new MenuBar();
Menu menuFile = new Menu();
MenuItem menuFileExit = new MenuItem();
abel("文件");
abel("退出");
// Add action the menu button
ctionListener
(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
owClosed();
}
}
);
(menuFileExit);
(menuFile);
setTitle("我的聊天程序");
setMenuBar(menuBar);
setSize(new Dimension(310, 500));
esizable(false);
// Add Window listener.
indowListener
(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
owClosed();
}
}
);
}
/**
* Shutdown procedure when run as an application.
*/
protected void windowClosed() {
// TODO: Check if it is safe to close the application
// Exit application.
e();
(0);
}
public static void main(String[] args) {
// Create application frame.
Chatp2pFrame frame = new Chatp2pFrame();
// Show frame
isible(true);
}
}