package d;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class Serverapp_UDP extends WindowAdapter implements ActionListener,KeyListener{
TextField str_send;
Label label;
TextArea msg;
Button send,exit;
Panel pl;
String hostname;
DatagramSocket receiveSocket,sendSocket;
DatagramPacket receivePacket,sendPacket;
public void display(){
Frame f=new Frame("在线聊天---服务器");
f.setSize(400,350);
f.setLocation(400,400);
f.setBackground(Color.blue);
pl=new Panel();
f.add(pl,"South");
msg=new TextArea();
msg.setSize(100,250);
msg.setBackground(Color.white);
msg.setEditable(false);
f.add(msg);
label=new Label("发送消息");
pl.add(label);
str_send=new TextField(20);
pl.add(str_send);
str_send.addKeyListener(this);
send=new Button("发送");
pl.add(send);
send.addActionListener(this);
exit=new Button("退出");
pl.add(exit);
exit.addActionListener(this);
f.addWindowListener(this);
f.setVisible(true);
try{
sendSocket=new DatagramSocket(5000);
}
catch(Exception e){
msg.append(e+"\n");
}
}
public void receiveMessage(){
try{
receiveSocket=new DatagramSocket(3333);
while(true){
byte[]buf=new byte[500];
receivePacket=new DatagramPacket(buf,buf.length);
receivePacket=new DatagramPacket(buf,buf.length);
receiveSocket.receive(receivePacket);
if(receivePacket.getLength()==0){
System.out.println("消息为空");
continue;
}
ByteArrayInputStream bin=new ByteArrayInputStream(receivePacket.getData());
BufferedReader reader=new BufferedReader(new InputStreamReader(bin));
msg.append("客户端:"+reader.readLine());
msg.append("\n");
reader.close();
bin.close();
}
}
catch(Exception e){
msg.append(e+"\n");
}
}
public void sendMessage(){
try{
String s=str_send.getText();
str_send.setText("");
msg.append("服务器:"+s+"\n");
ByteArrayOutputStream out=new ByteArrayOutputStream();
PrintStream pout=new PrintStream(out);
pout.print(s);
byte buf[]=out.toByteArray();
sendPacket=new DatagramPacket(buf,buf.length,InetAddress.getByName(hostname),6560);
sendSocket.send(sendPacket);
buf=null;
}
catch(Exception err){
msg.append(err+"\n");
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==str_send){
sendMessage();
}
if(e.getSource()==exit){
System.out.println("聊天程序已关闭,再见!\n");
System.exit(0);
}
}
public void windowClosing(WindowEvent e){
System.out.println("聊天程序已关闭,再见!\n");
System.exit(0);
}
public void keyPressed(KeyEvent e){
if(e.getSource()==str_send){
if(e.getKeyChar()==KeyEvent.VK_ENTER){
sendMessage();
}
}
}
public static void main(String arg[]){
Serverapp_UDP app=new Serverapp_UDP();
app.display();
app.receiveMessage();
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){}
}