糯米文學吧

位置:首頁 > IT認證 > JAVA認證

java編寫即時聊天程序

JAVA認證1.13W

怎樣用java編寫一個即時聊天程序呢?下面yjbys小編就為大家分享最新的`java即時聊天程序編寫方法,一起來看看吧!

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);

}

}

標籤:JAVA 即時 編寫