java最简单聊天代码 java简易聊天

用JAVA 编写简单网络聊天程序/**
* 基于UDP协议的聊天程序
*
*2007.9.18
* */
//导入包
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.net.*;
public class Chat extends JFrame implements ActionListener
{
//广播地址或者对方的地址
public static final String sendIP = "172.18.8.255";
//发送端口9527
public static final int sendPort = 9527;
JPanel p = new JPanel();
List lst = new List();//消息显示
JTextField txtIP = new JTextField(18); //填写IP地址
JTextField txtMSG = new JTextField(20); //填写发送消息
JLabel lblIP = new JLabel("IP地址:");
JLabel lblMSG = new JLabel("消息:");
JButton btnSend = new JButton("发送");
byte [] buf;
//定义DatagramSocket的对象必须进行异常处理
//发送和接收数据报包的套接字
DatagramSocket ds = null;
//=============构造函数=====================
public Chat()
{
CreateInterFace();
//注册消息框监听器
txtMSG.addActionListener(this);
btnSend.addActionListener(this);
try
{
//端口:9527
ds =new DatagramSocket(sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
//============接受消息============
//匿名类
new Thread(new Runnable()
{
public void run()
{
byte buf[] = new byte[1024];
//表示接受数据报包
while(true)
{
try
{
DatagramPacket dp = new DatagramPacket(buf,1024,InetAddress.getByName(txtIP.getText()),sendPort);
ds.receive(dp);
lst.add("【消息来自】◆"dp.getAddress().getHostAddress()"◆" "【说】:"new String (buf,0,dp.getLength()) /*dp.getPort()*/,0);
}
catch(Exception e)
{
if(ds.isClosed())
{
e.printStackTrace();
}
}
}
}
}).start();
//关闭窗体事件
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.out.println("test");
int n=JOptionPane.showConfirmDialog(null,"是否要退出?","退出",JOptionPane.YES_NO_OPTION);
if(n==JOptionPane.YES_OPTION)
{
dispose();
System.exit(0);
ds.close();//关闭ds对象//关闭数据报套接字
}
}
});
}
//界面设计布局
public void CreateInterFace()
{
this.add(lst,BorderLayout.CENTER);
this.add(p,BorderLayout.SOUTH);
p.add(lblIP);
p.add(txtIP);
p.add(lblMSG);
p.add(txtMSG);
p.add(btnSend);
txtIP.setText(sendIP);
//背景颜色
lst.setBackground(Color.yellow);
//JAVA默认风格
this.setUndecorated(true);
this.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
this.setSize(600,500);
this.setTitle("〓聊天室〓");
this.setResizable(false);//不能改变窗体大小
this.setLocationRelativeTo(null);//窗体居中
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setVisible(true);
txtMSG.requestFocus();//消息框得到焦点
}
//===============================Main函数===============================
public static void main(String[]args)
{
new Chat();
}
//================================发送消息===============================
//消息框回车发送消息事件
public void actionPerformed(ActionEvent e)
{
//得到文本内容
buf = txtMSG.getText().getBytes();
//判断消息框是否为空
if (txtMSG.getText().length()==0)
{
JOptionPane.showMessageDialog(null,"发送消息不能为空","提示",JOptionPane.WARNING_MESSAGE);
}
else{
try
{
InetAddress address = InetAddress.getByName(sendIP);
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
ds.send(dp);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
txtMSG.setText("");//清空消息框
//点发送按钮发送消息事件
if(e.getSource()==btnSend)
{
buf = txtMSG.getText().getBytes();
try
{
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}
txtMSG.setText("");//清空消息框
txtMSG.requestFocus();
}
}
}
Java简单聊天程序package com.kum.im.hrserver.test;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.awt.*;
import java.awt.event.*;
public class ChatClient {
private SocketChannel sc = null;
private String name = null;
private Frame f;
private TextArea ta;
private TextField tf;
private boolean runnable = true;
public static void main(String[] args){
ChatClient cc = new ChatClient();
cc.createUI();
cc.inputName();
cc.connect();
new ReceiveThread(cc,cc.getTextArea()).start();
}
public SocketChannel getSc(){
return sc;
}
public void setName(String name){
this.name = name;
}
public TextArea getTextArea(){
return ta;
}
public TextField getTextField(){
return tf;
}
public boolean getRunnable(){
return runnable;
}
public void stop(){
runnable = false;
}
public void shutDown(){
try{
sc.write(ByteBuffer.wrap("bye".getBytes("UTF-8")));
ta.append("Exit in 5 seconds!");
this.stop();
Thread.sleep(5000);
sc.close();
}catch(Exception e){
e.printStackTrace();
}
System.exit(0);
}
public void createUI(){
f = new Frame("Client");
ta = new TextArea();
ta.setEditable(false);
tf = new TextField();
Button send = new Button("Send");
Panel p = new Panel();
p.setLayout(new BorderLayout());
p.add(tf,"Center");
p.add(send,"East");
f.add(ta,"Center");
f.add(p,"South");
MyClientListener listener = new MyClientListener(this);
send.addActionListener(listener);
tf.addActionListener(listener);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
ChatClient.this.shutDown();
}
});
f.setSize(400,400);
f.setLocation(600,0);
f.setVisible(true);
tf.requestFocus();
}
public boolean connect(){
try{
sc = SocketChannel.open();
//"zlg"为目标计算机名
InetSocketAddress isa = new InetSocketAddress("192.168.1.43",8814);
sc.connect(isa);
sc.configureBlocking(false);
sc.write(ByteBuffer.wrap(name.getBytes("UTF-8")));
}catch(Exception e){
e.printStackTrace();
}
return true;
}
public void inputName(){
String name = javax.swing.JOptionPane.showInputDialog("Input Your Name:");
this.setName(name);
f.setTitle(name);
}
}
class MyClientListener implements ActionListener{
private ChatClient client;
public MyClientListener(ChatClient client){
this.client = client;
}
public void actionPerformed(ActionEvent e){
TextField tf = client.getTextField();
String info = tf.getText();
if(info.equals("bye")){
client.shutDown();
}else{
try{
client.getSc().write(ByteBuffer.wrap(info.getBytes("UTF-8")));
}catch (Exception e1) {
e1.printStackTrace();
}
}
tf.setText("");
tf.requestFocus();
}
}
class ReceiveThread extends Thread{
private ChatClient client;
private TextArea ta;
public ReceiveThread(ChatClient client,TextArea ta){
this.client = client;
this.ta = ta;
}
public void run(){
SocketChannel sc = client.getSc();
ByteBuffer byteBuffer = ByteBuffer.allocate(2048);
CharBuffer charBuffer = null;
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
String msg = null;
int n = 0;
try{
while(client.getRunnable()){
n = sc.read(byteBuffer);
if(n0){
byteBuffer.flip();
charBuffer = decoder.decode(byteBuffer);
msg = charBuffer.toString();
ta.append(msg"\n");
}
byteBuffer.clear();
Thread.sleep(500);
}
}catch(Exception e){
e.printStackTrace();
System.exit(0);
}
}
}
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.net.*;
import java.util.*;
public class ICQServer {
private Selector selector = null;
private ServerSocketChannel ssc = null;
//服务器端通信端口号
private int port = 8814;
//在线用户列表
private HashtableString, SocketChannel userList = null;
public ICQServer() {}
public ICQServer(int port) {
this.port = port;
}
//初始化服务器
public void init() {
try {
//创建选择器对象
selector = Selector.open();
//创建ServerSocketChannel
ssc = ServerSocketChannel.open();
//设置ServerSocketChannel为非阻塞模式
ssc.configureBlocking(false);
InetAddress ip = InetAddress.getLocalHost();
System.out.println("主机地址 -------- "ip);
InetSocketAddress isa = new InetSocketAddress(ip, port);
//将与本通道相关的服务器套接字对象绑定到指定地址和端口
ssc.socket().bind(isa);
//创建在线用户列表
userList = new HashtableString, SocketChannel ();
}
catch (IOException e) {
System.out.println("初始化服务器时异常 , 原因--------"e.getMessage());
}
}
//启动服务器
public void start() {
try {
//将ServerSocketChannel注册到Selector上 , 准备接收新连接请求
SelectionKey acceptKey = ssc.register(selector, SelectionKey.OP_ACCEPT);
SocketChannel sc;
int n;
String name; //用户名
String msg; //用户发言信息
while (true) {
//选择当前所有处于就绪状态的通道所对应的选择键,并将这些键组成已选择键集
n = selector.select(); //n为已选择键集中键的个数
if (n0) {
//获取此选择器的已选择键集 。
Set readyKeys = selector.selectedKeys();
Iterator it = readyKeys.iterator();
//遍历当前已选择键集
while (it.hasNext()) {
SelectionKey key = (SelectionKey) it.next();
//从当前已选择键集中移除当前键,避免重复处理
it.remove();
//如果当前键对应的通道已准备好接受新的套接字连接
if (key.isAcceptable()) {
//获取当前键对应的可选择通道(ServerSocketChannel)
ssc = (ServerSocketChannel) key.channel();
//接收新的套接字连接请求,返回新建的SocketChannel
sc = (SocketChannel) ssc.accept();
//如果有新用户接入
if (sc != null) {
//接收新上线用户姓名
name = readMessage(sc);
//设置新建的SocketChannel为非阻塞模式
sc.configureBlocking(false);
//将新建的SocketChannel注册到Selector上 , 准备进行数据"写"操作 ,
//并将当前用户名以附件的方式附带记录到新建的选择键上 。
SelectionKey newKey = sc.register(selector,
SelectionKey.OP_WRITE, name);
//将新上线用户信息加入到在线用户列表
userList.put(name, sc);
//发送"新用户上线"通知
transmitMessage(name" in!", "--Server Info--");
}
}
//否则,如果当前键对应的通道已准备好进行"写"操作
else if (key.isWritable()) {
//获取当前键对应的可选择通道(SocketChannel)
sc = (SocketChannel) key.channel();
//接收该通道相应用户的发言信息
msg = readMessage(sc);
//获取选择键上附带记录的当前用户名
name = key.attachment().toString();
//如果用户提出要下线
if (msg.equals("bye")) {
//从在线用户列表中移除当前用户
userList.remove(name);
//注销当前选择键对应的注册关系
key.cancel();
//关闭当前可选择通道
sc.close();
//发送"用户下线"通知
transmitMessage(name" out!", "--Server Info--");
}
//否则 , 如果接收到的用户发言信息非空("")
else if (msg.length()0) {
//转发用户发言信息
transmitMessage(msg, name);
}
}
}
}
//延时循环,降低服务器端处理负荷
Thread.sleep(500);
}
}
catch (Exception e) {
System.out.println("启动服务器时异常,原因--------"e.getMessage());
}
}
//转发用户发言信息
public void transmitMessage(String msg, String name) {
try {
ByteBuffer buffer = ByteBuffer.wrap( (name":"msg).getBytes("UTF-8"));
//将字节数组包装到缓冲区中
Collection channels = userList.values();
SocketChannel sc;
for (Object o : channels) {
sc = (SocketChannel) o;
sc.write(buffer);
//将缓冲区数据写入聊天面板(TextArea)
buffer.flip();
//将缓冲区ByteBuffer的极限值设置为当前数据实际大小,将缓冲区的值设置为0
}
}
catch (Exception e) {
System.out.println("转发用户发言信息时异常,原因--------"e.getMessage());
}
}
//接收用户发言信息
public String readMessage(SocketChannel sc) {
String result = null;
int n = 0;
ByteBuffer buf = ByteBuffer.allocate(1024);
try {
n = sc.read(buf);
buf.flip();
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode(buf);
result = charBuffer.toString();
}
catch (IOException e) {
System.out.println("接收用户发言信息时异常,原因--------"e.getMessage());
}
return result;
}
public static void main(String args[]) {
ICQServer server = new ICQServer();
server.init();
server.start();
}
}
急求一个JAVA编写的局域网聊天代码?不要求很复杂 。只要可以在两台机子上简单的对话就可以 。//以下引入包
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.applet.*;
public class regit extends JApplet implements ActionListener,ItemListener//接口
{
String s=null;
//对象的声明
JLabel labelname,labelpass,labelsxe,labeladdress,labelmail,labelphone;//标签
JTextField textname,textaddress,textmail,textphone;//文本框
JRadioButton r1,r2;//单选按纽
ButtonGroup bg;//组
JPasswordField textpass;//密码域
JButton buttonregit,buttonreset;//注册按纽 重写按纽
JPanel p;//面板
String sex;//定义性别字符串
URL url;//统一资源定位
BufferedWriter out1,out2;//流
BufferedReader in;
//布局方式
GridBagLayout gbl;
GridBagConstraints gc;
AppletContext co;//接口
//初始化
public void init()
{
//new 对象
labelname=new JLabel("用 户 名:");
labelpass=new JLabel("用户密码:");
labelsxe=new JLabel("性别:");
labeladdress=new JLabel("地址:");
labelmail=new JLabel("电子邮件:");
labelphone=new JLabel("联系电话:");
textname=new JTextField(15); textname.setForeground(Color.red);
textname.setToolTipText("请在这输入你的用户名");
textaddress=new JTextField(15);textaddress.setForeground(Color.red);
textaddress.setToolTipText("请在这输入你的地址");
textmail=new JTextField(15); textmail.setForeground(Color.red);
textmail.setToolTipText("请在这里输入你的E-mail地址");
textphone=new JTextField(15); textphone.setForeground(Color.red);
textphone.setToolTipText("请在这输入你的电话号码");
r1=new JRadioButton("男"); r1.setBackground(new Color(47,177,210));//设置颜色
r2=new JRadioButton("女"); r2.setBackground(new Color(47,177,210));//设置颜色
bg=new ButtonGroup();
bg.add(r1);bg.add(r2);//加入组,实现单选
textpass=new JPasswordField(15);
textpass.setToolTipText("在这里输入密码");
textpass.setForeground(Color.red);
buttonregit=new JButton("注册"); buttonregit.setBackground(new Color(47,177,210));//设置颜色
buttonregit.setToolTipText("点击按纽完成注册");
buttonreset=new JButton("填写"); buttonreset.setBackground(new Color(47,177,210));//设置颜色
buttonreset.setToolTipText("点击按纽刷新重写");
gbl=new GridBagLayout(); ///////////////////////////////////////
gc=new GridBagConstraints(); //////采用GridBagLayout布局方式////////
p=new JPanel();
p.setLayout(gbl);
p.setBackground(new Color(47,177,210));
this.getContentPane().add(p);//加入面板
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=2;
gbl.setConstraints(labelname,gc);
p.add(labelname);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=2;
gbl.setConstraints(textname,gc);
p.add(textname);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=4;
gbl.setConstraints(labelpass,gc);
p.add(labelpass);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=4;
gbl.setConstraints(textpass,gc);
p.add(textpass);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=6;
gbl.setConstraints(labelsxe,gc);
p.add(labelsxe);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=6;
gbl.setConstraints(r1,gc);
p.add(r1);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=5;
gc.gridy=6;
gbl.setConstraints(r2,gc);
p.add(r2);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=8;
gbl.setConstraints(labeladdress,gc);
p.add(labeladdress);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=8;
gbl.setConstraints(textaddress,gc);
p.add(textaddress);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=10;
gbl.setConstraints(labelmail,gc);
p.add(labelmail);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=10;
gbl.setConstraints(textmail,gc);
p.add(textmail);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=12;
gbl.setConstraints(labelphone,gc);
p.add(labelphone);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=12;
gbl.setConstraints(textphone,gc);
p.add(textphone);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=16;
gbl.setConstraints(buttonregit,gc);
p.add(buttonregit);
gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=16;
gbl.setConstraints(buttonreset,gc);
p.add(buttonreset);
/////////////////////////////////////////////
co=this.getAppletContext();
/////////////////////////////////////////////
buttonregit.addActionListener(this);//按纽事件的监听
buttonreset.addActionListener(this);//按纽事件的监听
r1.addItemListener(this);//选择事件的监听
r2.addItemListener(this);//选择事件的监听
textphone.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
//注册按纽事件
if(e.getSource()==buttonregit)
{
String s1=textname.getText(); ////////////////////
String s2=new String(textpass.getPassword());////////////////////
String s3=textaddress.getText(); // 定义字符串 //
String s4=textmail.getText(); ////////////////////
String s5=textphone.getText(); ////////////////////
//判断注册资料 信息 是否为空
if(s1.length()==0 || s2.length()==0 ||s3.length()==0 ||s4.length()==0 ||s5.length()==0)
{
int error=JOptionPane.INFORMATION_MESSAGE;
JOptionPane.showMessageDialog(null,"资料不能为空,请重新注册!","【温馨提示】",error);
return;//弹出对话框并返回
}
try//写入到txt文件
{
in=new BufferedReader(new FileReader("d:\\迷离视线聊天室\\password.txt"));
}
catch(Exception ee){}
String ss=s1;
try
{
while((s=in.readLine())!=null)
{
if(s.startsWith(ss))
{
JOptionPane.showMessageDialog(null,"用户名已经存在 , 请更换名字!");
textname.setText("");//设置为空,重新输入
textpass.setText("");
textaddress.setText("");
textmail.setText("");
textphone.setText("");
return;
}
}
}
catch(Exception ee){}
///////////////////////////以上代码判断是否有同名
{
try
{
out1=new BufferedWriter(new FileWriter("d:\\迷离视线聊天室\\password.txt",true));
out2=new BufferedWriter(new FileWriter("d:\\迷离视线聊天室\\message.txt",true));
}//创建文件
catch(Exception ee)
{}
try
{
out1.write(s1 "#" s2);//写
out1.newLine();
out2.write("用户名:" s1);
out2.newLine();
out2.write("密码:" s2);
out2.newLine();
out2.write("性别:" sex);
out2.newLine();
out2.write("地址:" s3);
out2.newLine();
out2.write("电子邮件:" s4);
out2.newLine();
out2.write("电话:" s5);
out2.newLine();
out1.flush();
out2.flush();//清理缓冲
out1.close();
out2.close();
}
catch(Exception ee)
{}
JOptionPane.showMessageDialog(null,"注册成功!");
try
{
String qss="";
url=new url(/qss);//连接上网址
co.showDocument(url);
}
catch(Exception exx)
{}
}
}
//////////////////////以下为回车事件
if(e.getSource()==textphone)
{
String s1=textname.getText(); ////////////////////
String s2=new String(textpass.getPassword());////////////////////
String s3=textaddress.getText(); // 定义字符串 //
String s4=textmail.getText(); ////////////////////
String s5=textphone.getText(); ////////////////////
//判断注册资料 信息 是否为空
if(s1.length()==0 || s2.length()==0 ||s3.length()==0 ||s4.length()==0 ||s5.length()==0)
{
int error=JOptionPane.INFORMATION_MESSAGE;
JOptionPane.showMessageDialog(null,"资料不能为空,请重新注册!","【温馨提示】",error);
return;//弹出对话框并返回
}
try//写入到txt文件
{
in=new BufferedReader(new FileReader("d:\\迷离视线聊天室\\password.txt"));
}
catch(Exception ee){}
String ss=s1;
try
{
while((s=in.readLine())!=null)
{
if(s.startsWith(ss))
{
JOptionPane.showMessageDialog(null,"用户名已经存在 , 请更换名字!");
textname.setText("");//设置为空 , 重新输入
textpass.setText("");
textaddress.setText("");
textmail.setText("");
textphone.setText("");
return;
}
}
}
catch(Exception ee){}
///////////////////////////以上代码判断是否有同名
{
try
{
out1=new BufferedWriter(new FileWriter("d:\\迷离视线聊天室\\password.txt",true));
out2=new BufferedWriter(new FileWriter("d:\\迷离视线聊天室\\message.txt",true));
}//创建文件
catch(Exception ee)
{}
try
{
out1.write(s1 "#" s2);//写
out1.newLine();
out2.write("用户名:" s1 "密码:" s2 "性别:" sex "地址:" s3 "电子邮件:" s4 "电话:" s5);//写
out2.newLine();
out1.flush();
out2.flush();//清理缓冲
out1.close();
out2.close();
}
catch(Exception ee)
{}
JOptionPane.showMessageDialog(null,"注册成功!");
try
{
String qss="";
url=new url(/qss);//连接上网址
co.showDocument(url);
}
catch(Exception exx)
{}
}
}
if(e.getSource()==buttonreset)//刷新重写事件
{
textname.setText("");
textpass.setText("");
textaddress.setText("");
textmail.setText("");
textphone.setText("");
}
}
//////////////////////////////////////////
//
public void itemStateChanged(ItemEvent ex)
{
if(ex.getSource()==r1)
{
sex=new String("男");
}
else if(ex.getSource()==r2)
{
sex=new String("女");
}
}
}
参考资料:试试看,刚在网上找的
谁可以给我一个Java设计的最最最最最简单的有服务端和客户端的聊天程序这个是UDP写java最简单聊天代码的
这个是客户端
import java.awt.event.*;
import java.net.*;
import javax.swing.*;
public class UDPClientDemo extends JFrame{
String host="localhost"; //服务器地址
int port=2345; //端口号
public UDPClientDemo(){
try{
DatagramSocket socket=new DatagramSocket(); //实例化一个数据报Socket
InetAddress address=InetAddress.getByName(host); //服务器地址
byte[] buffer=new byte[256]; //缓冲区
DatagramPacket packet=new DatagramPacket(buffer,buffer.length,address,port); //实例化一个数据报
socket.send(packet); //发送报文
packet=new DatagramPacket(buffer,buffer.length);
socket.receive(packet); //接受回应
String message=new String(packet.getData()); //得到报文信息
System.out.println("Received from: " packet.getAddress()); //显示信息源地址
System.out.println(message); //显示服务器返回信息
socket.close(); //关闭端口
}
catch (Exception ex){
ex.printStackTrace(); //输出出错信息
}
}
public static void main(String[] args){
new UDPClientDemo();
}
}
这个是服务器
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import javax.swing.*;
public class UDPServerDemo extends JFrame{
int port=2345; //端口号
public UDPServerDemo(){
try{
byte[] buffer=new byte[256]; //缓冲区数组
DatagramSocket socket=new DatagramSocket(port); //实例化数据报Socket
DatagramPacket packet;
System.out.println("Server start..."); //输出运行信息
while (true){
packet=new DatagramPacket(buffer,buffer.length); //实例化数据报
socket.receive(packet); //接受请求
InetAddress target=packet.getAddress();
System.out.println("Received from" target); //输出请求地址
int port=packet.getPort(); //得到接收端口
byte[] message="This is server,Who are you?".getBytes(); //服务器返回信息
packet=new DatagramPacket(message,message.length,target,port); //实例化数据报
socket.send(packet); //发送数据报
}
}
catch (Exception ex){
ex.printStackTrace(); //输出出错信息
}
}
public static void main(String[] args){
new UDPServerDemo();
}
}
这个其实还可以简化 做成最简单java最简单聊天代码的 但是这个两个代码里面你可以学习到很多知识 很经典java最简单聊天代码的代码
大家有没有基于一对一聊天的最简单的java聊天代码先运行服务端 再运行客户端就能对话了
服务端
package Liaotian;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class fwjiemian extends Frame implements ActionListener{
JTextArea lt;
TextField sr;
Button fs;
Panel xia;
ServerSocket ss;
Socket s;
BufferedReader br;
PrintWriter pw;
BufferedReader in;
public fwjiemian(){
lt=new JTextArea();
lt.setLineWrap(true);
sr=new TextField();
fs=new Button("发送");
xia=new Panel(new GridLayout(1,2));
xia.add(sr);
xia.add(fs);
this.add(lt);
this.add(xia,BorderLayout.SOUTH);
this.setResizable(false);
this.setSize(400, 500);
this.setLocation(350, 100);
this.setTitle("服务器");
this.setVisible(true);
fs.addActionListener(this);
//创建客户端 接受消息
try {
lt.setFont(newjava.awt.Font("宋体",0,15));
ss=new ServerSocket(8888);
lt.append("服务器已启动,等待客户端接入..." "\n" "\n");
s=ss.accept();
lt.append("客户端已接入..." "\n" "\n");
while(true){
//获取时间
SimpleDateFormat sm=new SimpleDateFormat("HH:mm:ss");
System.out.println(sm.format(new Date()));
//接受消息
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
String info=br.readLine();
lt.append("☆ 客户端:" info "" sm.format(new Date()) "\n" "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new fwjiemian();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==fs){
try {
//获取时间
SimpleDateFormat sm=new SimpleDateFormat("HH:mm:ss");
System.out.println(sm.format(new Date()));
//发送消息
String infotokehu=sr.getText();
pw=new PrintWriter(s.getOutputStream(),true);
pw.println(infotokehu);
lt.setFont(newjava.awt.Font("宋体",0,15));
lt.append("

    推荐阅读