java

位置:IT落伍者 >> java >> 浏览文章

Java UDP聊天程序


发布日期:2019年04月25日
 
Java UDP聊天程序

import javaawtBorderLayout;

import javaawtList;

import javaawtTextField;

import javaawteventActionEvent;

import javaawteventActionListener;

import javaioIOException;

import DatagramPacket;

import DatagramSocket;

import InetAddress;

import SocketException;

import UnknownHostException;

import javaxswingJFrame;

import javaxswingJPanel;

public class netchat {

JFrame jf=new JFrame(我的网络聊天程序);

List l=new List();

JPanel jp=new JPanel();

TextField tip=new TextField();

TextField tdata=new TextField();

DatagramSocket ds;

//DatagramPacket dp;

public netchat()

{

tipsetText();

try {

ds=new DatagramSocket();

} catch (SocketException e) {

// TODO Autogenerated catch block

eprintStackTrace();

}

new Thread(new Runnable()

{

DatagramPacket dp;

public void run()

{

byte [] buf=new byte[];

dp=new DatagramPacket(buf);

//

// byte[] buf=new byte[];

// dp=new DatagramPacket(buf);

while(true)

{

try {

dsreceive(dp);

// ladd(dpgetAddress()getHostName()+say:+new String(bufdpgetLength()) );

ladd(dpgetAddress()getHostAddress()+ say:+new String(buf+dpgetLength()) );

} catch (IOException e) {

// TODO Autogenerated catch block

eprintStackTrace();

}

}

}

})start();

}

public static void main(String[] args) {

// TODO Autogenerated method stub

new netchat()init();

}

private void init()

{

jfadd(l);

jpadd(tipBorderLayoutWEST);

jpadd(tdataBorderLayoutEAST);

jfadd(jpBorderLayoutSOUTH);

jfsetSize( );

jfsetVisible(true);

jfsetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);

tdataaddActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent e)

{

// byte[] buf;

// buf=egetActionCommand()getBytes();

// DatagramPacket dp;

// try

// {

// dp=new DatagramPacket(bufbuflengthInetAddressgetByName(tipgetText()));

// dssend(dp);

//

byte [] buf;

buf=egetActionCommand()getBytes();

DatagramPacket dp;

try {

dp= new DatagramPacket(bufbuflengthInetAddressgetByName(tipgetText()) );

dssend(dp);

} catch (UnknownHostException e) {

// TODO Autogenerated catch block

eprintStackTrace();

} catch (IOException e) {

// TODO Autogenerated catch block

eprintStackTrace();

}

((TextField)egetSource())setText();

}

});

}

}

               

上一篇:JAVA实现httpClient实例

下一篇:Java类 精彩问答