📄 serverapp_udp.java
字号:
//Arial Black NARROW
//Serverapp_UDP.java
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,350);
f.setBackground(Color.red);
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);
str_send.addActionListener(this);
exit = new Button("退出");
pl.add(exit);
exit.addActionListener(this);
f.addWindowListener(this);
f.setVisible(true);
try
{
//sendSocket = new DatagramSocket(5000);
sendSocket = new DatagramSocket();
}
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("The Message Is Blank,please type it again!!");
continue;
}
ByteArrayInputStream bin = new ByteArrayInputStream(receivePacket.getData());
BufferedReader reader = new BufferedReader (new InputStreamReader(bin));
msg.append("Client:"+reader.readLine());
msg.append("\n");
bin.close();
}
}
catch(Exception e)
{
msg.append(e+"\n");
}
}
public void sendMessage()
{
try
{
String s = str_send.getText();
str_send.setText(" ");
msg.append("Server:" +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),3001);
sendSocket.send(sendPacket);
buf = null;
}
catch(Exception err)
{
msg.append(err+ "\n");
}
}
public void actionPerformed(ActionEvent e )
{
if(e.getSource()==send)
{
sendMessage();
}
if(e.getSource()==exit)
{
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 void windowClosing(WindowEvent e)
{
System.out.println("聊天程序已关闭,再见!\n");
System.exit(0);
}
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){}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -