在线等~~很急啊 ,难题,恳请各位高手帮忙。

时间:2021-10-08 18:52:56
我有这么段代码;还没写完,可能还有错,要实现的就是一个简单的聊天,能接受到对方信息,同时把信息保存起来。不要写的太难,简单越好,功能也不要很强大。
恳请大家帮忙。先谢过了。
我还是初学者,很多不会,请大家多多指教。

代码如下:
/*
 * @(#)Chat.java 1.0 07/11/01
 *
 * You can modify the template of this file in the
 * directory ..\JCreator\Templates\Template_1\Project_Name.java
 *
 * You can also create your own project template by making a new
 * folder in the directory ..\JCreator\Template\. Use the other
 * templates as examples.
 *
 */
package myprojects.chat;

import java.awt.*;
import java.awt.event.*;
import java.net.*;

class Chat extends Frame {
List lst=new List(6);
TextField tfIP = new TextField(15);
TextField tfData = new TextField(20);
DatagramSocket ds = null;

public Chat() {
try
{
ds=new DatagramSocket(3000);
}
catch(Exception e)
{
                    e.printStackTrace();
}
this.add(lst,"South");
Panel p = new Panel();
this.add(p,"North");

p.setLayout(new BorderLayout());
p.add(tfIP,"West");
p.add(tfData,"East");

new Thread(new Runnable()
{
public void run()
{
byte [] buf=new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,1024);
while(true)

try
{   
ds.receive(dp);
lst.add(new String(/*dp.getData()*/nof,0,dp.getLength())+
"  from  "+dp.getAddress().getHostAddress()+":"+
dp.getPort());
}
catch (Exception e)
{
if(!ds.isClosed())
{
e.printStackTrace();
}
}
}
}
}).start();

tfData.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
byte [] buf;
buf = tfData.getText().getBytes();
try
{
DatagramPacket dp=new DatagramPacket(buf,buf.length,
InetAddress.getByName(tfIP.getText()),3000);
ds.send(dp);
}
catch (Exception ex)
{
ex.printStackTrace();
}
tfData.setText("");
}
});
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
ds.close();
dispose();
System.exit(0);
}
});
}

public static void main(String args[]) {
System.out.println("Starting Chat...");
Chat mainFrame = new Chat();
mainFrame.setSize(300, 300);
mainFrame.setTitle("Chat");
mainFrame.setVisible(true);
mainFrame.setResizable(false);
}
}

9 个解决方案

#1


友情up

#2


同是小星星,帮顶

#3


学习一下,希望有大虾帮忙.

#4


package com.chat;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;

public class Chat1
{
private JFrame frame;
private Container contentPane;
private JTextField tf1;
private JTextArea ta,tb;
private JButton btnCon,btnSend,btnExit;
private JRadioButton rb1;
private JRadioButton rb2;
private String strbuf="";
private DatagramSocket serverSocket,clientSocket;

public Chat1()
{
frame=new JFrame("聊天室");
frame.setSize(460,460);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
contentPane=frame.getContentPane();
initGUI();
}

public void initGUI()
{
contentPane.setLayout(new BorderLayout());
JPanel panel1=new JPanel(new GridLayout(3,1));

JPanel p11=new JPanel(new FlowLayout(FlowLayout.LEFT));
p11.add(new JLabel("UDP连接程序"));

JPanel p12=new JPanel(new FlowLayout(FlowLayout.LEFT));
rb1=new JRadioButton("服务器端");
rb2=new JRadioButton("客户端");
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);
bg.add(rb2);
p12.add(rb1);
p12.add(rb2);
p12.add(new JLabel("连接状态"));
tf1=new JTextField(20);
tf1.setEditable(false);
p12.add(tf1);

panel1.add(p11);
panel1.add(p12);

contentPane.add(panel1,BorderLayout.NORTH);

JPanel panel2=new JPanel(new FlowLayout(FlowLayout.LEFT));
panel2.add(new JLabel("收到的信息"));
ta=new JTextArea(10,30);
ta.setEditable(false);
panel2.add(ta);
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane pane=new JScrollPane(ta,v,h);
panel2.add(pane);
contentPane.add(panel2,BorderLayout.CENTER);

JPanel panel3=new JPanel(new GridLayout(2,1));

JPanel p31=new JPanel(new FlowLayout(FlowLayout.LEFT));
p31.add(new JLabel("发送信息"));
tb=new JTextArea(3,30);

p31.add(tb);

JPanel p32=new JPanel(new FlowLayout());
btnCon=new JButton("连接");
btnSend=new JButton("发送");
btnExit=new JButton("关闭连接");
btnSend.setEnabled(false);
btnExit.setEnabled(false);
p32.add(btnCon);
p32.add(btnSend);
p32.add(btnExit);

panel3.add(p31);
panel3.add(p32);
contentPane.add(panel3,BorderLayout.SOUTH);

ActionListener listener =new ActionListener(){
public void actionPerformed(ActionEvent e)
{
//服务器端或客户端的连接
if(e.getSource()==btnCon)
{
if(rb1.isSelected()==false&&rb2.isSelected()==false)
{
tf1.setText("请选择客户端或服务器端!");
return;
}
try
{
if(rb1.isSelected()==true)
{
tb.setText("");
rb1.setEnabled(false);
rb2.setEnabled(false);
Server server=new Server();
}
if(rb2.isSelected()==true)
{
rb1.setEnabled(false);
rb2.setEnabled(false);
tb.setText("");
Client client=new Client();
}
}catch(Exception e1)
{
tf1.setText("连接错误!");
}
}

//服务器端或客户端信息的发送
if(e.getSource()==btnSend)
{
try
{
strbuf=tb.getText();
if(strbuf.length()>0)
{
ta.append(strbuf+"\n");
}
tb.setText("");
byte [] buffer=new byte[strbuf.length()];
buffer=strbuf.getBytes();
DatagramPacket packet;
if(rb1.isSelected()==true)
{
packet=new DatagramPacket(buffer,buffer.length,new InetSocketAddress("localhost",902));
serverSocket.send(packet);
}
if(rb2.isSelected()==true)
{
packet=new DatagramPacket(buffer,buffer.length,new InetSocketAddress("localhost",901));
clientSocket.send(packet);
}

}catch(Exception e1)
{
e1.printStackTrace();
}
}
//服务器端或客户端的断开
if(e.getSource()==btnExit)
{
try
{
if(rb1.isSelected()==true)
{
serverSocket.close();
Thread.currentThread().interrupt();
}
if(rb2.isSelected()==true)
{
clientSocket.close();
Thread.currentThread().interrupt();
}
tf1.setText("离线");
btnCon.setEnabled(true);
btnSend.setEnabled(false);
btnExit.setEnabled(false);
}catch(Exception e1)
{
tf1.setText("关闭时发生错误!");
}


}
}
};

btnCon.addActionListener(listener);
btnSend.addActionListener(listener);
btnExit.addActionListener(listener);

}
//实现服务器端信息接收的成员内部类
public class Server implements Runnable
{
public Server()
{
(new Thread(this)).start();
}


public void run()
{
String s;
try
{
btnCon.setEnabled(false);
serverSocket=new DatagramSocket(901);
ta.setText(InetAddress.getLocalHost().getHostName()+"port:901"+"\n");
tf1.setText("连接中");
btnSend.setEnabled(true);
btnExit.setEnabled(true);

while(true)
{
//接收
byte [] buffer=new byte[256];
DatagramPacket packet=new DatagramPacket(buffer,buffer.length);
serverSocket.receive(packet);
s=new String(packet.getData());
s=s.trim();
if(s.length()>0)
{
ta.append("Client:       "+s+"\n");
}


}

}catch(Exception e1)
{
e1.printStackTrace();
}

}

}
//实现客户端信息接收的多线程内部类
public class Client implements Runnable
{
public Client()
{
(new Thread(this)).start();
}

public void run()
{
DatagramPacket packet;
String s;
try
{
btnCon.setEnabled(false);
clientSocket=new DatagramSocket(902);
ta.setText(InetAddress.getLocalHost().getHostName()+"port:902"+"\n");
tf1.setText("连接中");
btnSend.setEnabled(true);
btnExit.setEnabled(true);
while(true)
{
//接收
byte [] buffer=new byte[256];
packet=new DatagramPacket(buffer,buffer.length);
clientSocket.receive(packet);
s=new String(packet.getData());
s=s.trim();
if(s.length()>0)
{
ta.append("server:     "+s+"\n");
}


}

}catch(Exception e)
{
e.printStackTrace();
}
}


public void go()
{
frame.setVisible(true);
}

public static void main(String args[])
{
(new Chat1()).go();
}
}
有好几个文件,你先看 看不懂再问我

#5


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.net.*;

public class Chat
{
private JFrame chatFrame;
private Container container;

private JLabel addLabel;
private JTextField addTextField;
private JButton connectButton;
private JPanel connectPanel;
private JLabel stateLabel;

private JTextArea msgTextArea;
private JScrollPane msgPane;

private JTextField sendTextField;
private JButton sendButton;
private JPanel sendPanel;

private ServerSocket server;
private Socket clientSocket;
private PrintWriter pw;


public Chat()
{
chatFrame=new JFrame("聊天");
container=chatFrame.getContentPane();

addLabel=new JLabel("IP地址:");
addTextField=new JTextField(15);
connectButton=new JButton("连接");
stateLabel=new JLabel("当前状态:");
connectPanel=new JPanel();

msgTextArea=new JTextArea();
msgPane=new JScrollPane(msgTextArea);
msgTextArea.setEditable(false);
msgTextArea.setAutoscrolls(true);

sendTextField=new JTextField(50);
sendButton=new JButton("提交");
sendPanel=new JPanel();

initGUI();
}

private void initGUI()
{
connectPanel.setLayout(new FlowLayout(FlowLayout.LEFT,25,5));
connectPanel.add(addLabel);
connectPanel.add(addTextField);
connectPanel.add(connectButton);
connectPanel.add(stateLabel);

sendPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
sendPanel.add(sendTextField);
sendPanel.add(sendButton);

container.add(connectPanel,BorderLayout.NORTH);
container.add(msgPane,BorderLayout.CENTER);
container.add(sendPanel,BorderLayout.SOUTH);

chatFrame.setSize(800,600);
chatFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

ConnectListener conn=new ConnectListener();
connectButton.addActionListener(conn);
addTextField.addActionListener(conn);

SendListener send=new SendListener();
sendButton.addActionListener(send);
sendTextField.addActionListener(send);
}

public void go()
{
chatFrame.setVisible(true);
new Thread(new ConnectHost()).start();
}

private class ConnectHost implements Runnable
{
public void run()
{

while(true)
{
if (clientSocket!=null)
{
stateLabel.setText("当前状态:已连接...");
try
{
pw=new PrintWriter(clientSocket.getOutputStream(),true);
BufferedReader br=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String strResive;
while(true)
{
strResive=br.readLine();
if (!strResive.equals("null"))
msgTextArea.append(strResive+"\n");

}
}
catch(Exception e)
{
server=null;
clientSocket=null;
}

}
try
{

server=new ServerSocket(10000);
stateLabel.setText("当前状态:正在监听...");
clientSocket=server.accept();
stateLabel.setText("当前状态:已连接...");
}
catch(Exception e)
{
stateLabel.setText("当前状态:本地端口已被占用...");
}
}
}


}

private class SendListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
if (sendTextField.getText().trim().equals(""))
return;
if (clientSocket==null)
return;

pw.println(sendTextField.getText().trim());
msgTextArea.append(sendTextField.getText()+"\n");
sendTextField.setText("");
}
}

private class ConnectListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
if (addTextField.getText().trim().equals(""))
return;
String ipAddress=addTextField.getText().trim();
try
{
clientSocket=new Socket(ipAddress,10000);
stateLabel.setText("当前状态:已连接");
server.close();

}
catch(Exception e)
{
stateLabel.setText("当前状态:连接失败");
}
}
}


public static void main(String[] args)
{
new Chat().go();
}
}

#6


你把程序里的端口改成你的 就可以通信了,再有问题就是很小的问题了

#7


开源盛世嘛 呵呵!!!!希望大家有代码的都发下 大家交流交流

#8


   我自己写的聊天室没有写就放弃了,不会写啦
有时间来学习了.

#9


聊天室的实现就是Socket的问题,只要弄懂Socket,和Swing组件的事件的用法,说得白痴一点,很简单简单。。。

#1


友情up

#2


同是小星星,帮顶

#3


学习一下,希望有大虾帮忙.

#4


package com.chat;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;

public class Chat1
{
private JFrame frame;
private Container contentPane;
private JTextField tf1;
private JTextArea ta,tb;
private JButton btnCon,btnSend,btnExit;
private JRadioButton rb1;
private JRadioButton rb2;
private String strbuf="";
private DatagramSocket serverSocket,clientSocket;

public Chat1()
{
frame=new JFrame("聊天室");
frame.setSize(460,460);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
contentPane=frame.getContentPane();
initGUI();
}

public void initGUI()
{
contentPane.setLayout(new BorderLayout());
JPanel panel1=new JPanel(new GridLayout(3,1));

JPanel p11=new JPanel(new FlowLayout(FlowLayout.LEFT));
p11.add(new JLabel("UDP连接程序"));

JPanel p12=new JPanel(new FlowLayout(FlowLayout.LEFT));
rb1=new JRadioButton("服务器端");
rb2=new JRadioButton("客户端");
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);
bg.add(rb2);
p12.add(rb1);
p12.add(rb2);
p12.add(new JLabel("连接状态"));
tf1=new JTextField(20);
tf1.setEditable(false);
p12.add(tf1);

panel1.add(p11);
panel1.add(p12);

contentPane.add(panel1,BorderLayout.NORTH);

JPanel panel2=new JPanel(new FlowLayout(FlowLayout.LEFT));
panel2.add(new JLabel("收到的信息"));
ta=new JTextArea(10,30);
ta.setEditable(false);
panel2.add(ta);
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane pane=new JScrollPane(ta,v,h);
panel2.add(pane);
contentPane.add(panel2,BorderLayout.CENTER);

JPanel panel3=new JPanel(new GridLayout(2,1));

JPanel p31=new JPanel(new FlowLayout(FlowLayout.LEFT));
p31.add(new JLabel("发送信息"));
tb=new JTextArea(3,30);

p31.add(tb);

JPanel p32=new JPanel(new FlowLayout());
btnCon=new JButton("连接");
btnSend=new JButton("发送");
btnExit=new JButton("关闭连接");
btnSend.setEnabled(false);
btnExit.setEnabled(false);
p32.add(btnCon);
p32.add(btnSend);
p32.add(btnExit);

panel3.add(p31);
panel3.add(p32);
contentPane.add(panel3,BorderLayout.SOUTH);

ActionListener listener =new ActionListener(){
public void actionPerformed(ActionEvent e)
{
//服务器端或客户端的连接
if(e.getSource()==btnCon)
{
if(rb1.isSelected()==false&&rb2.isSelected()==false)
{
tf1.setText("请选择客户端或服务器端!");
return;
}
try
{
if(rb1.isSelected()==true)
{
tb.setText("");
rb1.setEnabled(false);
rb2.setEnabled(false);
Server server=new Server();
}
if(rb2.isSelected()==true)
{
rb1.setEnabled(false);
rb2.setEnabled(false);
tb.setText("");
Client client=new Client();
}
}catch(Exception e1)
{
tf1.setText("连接错误!");
}
}

//服务器端或客户端信息的发送
if(e.getSource()==btnSend)
{
try
{
strbuf=tb.getText();
if(strbuf.length()>0)
{
ta.append(strbuf+"\n");
}
tb.setText("");
byte [] buffer=new byte[strbuf.length()];
buffer=strbuf.getBytes();
DatagramPacket packet;
if(rb1.isSelected()==true)
{
packet=new DatagramPacket(buffer,buffer.length,new InetSocketAddress("localhost",902));
serverSocket.send(packet);
}
if(rb2.isSelected()==true)
{
packet=new DatagramPacket(buffer,buffer.length,new InetSocketAddress("localhost",901));
clientSocket.send(packet);
}

}catch(Exception e1)
{
e1.printStackTrace();
}
}
//服务器端或客户端的断开
if(e.getSource()==btnExit)
{
try
{
if(rb1.isSelected()==true)
{
serverSocket.close();
Thread.currentThread().interrupt();
}
if(rb2.isSelected()==true)
{
clientSocket.close();
Thread.currentThread().interrupt();
}
tf1.setText("离线");
btnCon.setEnabled(true);
btnSend.setEnabled(false);
btnExit.setEnabled(false);
}catch(Exception e1)
{
tf1.setText("关闭时发生错误!");
}


}
}
};

btnCon.addActionListener(listener);
btnSend.addActionListener(listener);
btnExit.addActionListener(listener);

}
//实现服务器端信息接收的成员内部类
public class Server implements Runnable
{
public Server()
{
(new Thread(this)).start();
}


public void run()
{
String s;
try
{
btnCon.setEnabled(false);
serverSocket=new DatagramSocket(901);
ta.setText(InetAddress.getLocalHost().getHostName()+"port:901"+"\n");
tf1.setText("连接中");
btnSend.setEnabled(true);
btnExit.setEnabled(true);

while(true)
{
//接收
byte [] buffer=new byte[256];
DatagramPacket packet=new DatagramPacket(buffer,buffer.length);
serverSocket.receive(packet);
s=new String(packet.getData());
s=s.trim();
if(s.length()>0)
{
ta.append("Client:       "+s+"\n");
}


}

}catch(Exception e1)
{
e1.printStackTrace();
}

}

}
//实现客户端信息接收的多线程内部类
public class Client implements Runnable
{
public Client()
{
(new Thread(this)).start();
}

public void run()
{
DatagramPacket packet;
String s;
try
{
btnCon.setEnabled(false);
clientSocket=new DatagramSocket(902);
ta.setText(InetAddress.getLocalHost().getHostName()+"port:902"+"\n");
tf1.setText("连接中");
btnSend.setEnabled(true);
btnExit.setEnabled(true);
while(true)
{
//接收
byte [] buffer=new byte[256];
packet=new DatagramPacket(buffer,buffer.length);
clientSocket.receive(packet);
s=new String(packet.getData());
s=s.trim();
if(s.length()>0)
{
ta.append("server:     "+s+"\n");
}


}

}catch(Exception e)
{
e.printStackTrace();
}
}


public void go()
{
frame.setVisible(true);
}

public static void main(String args[])
{
(new Chat1()).go();
}
}
有好几个文件,你先看 看不懂再问我

#5


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.io.*;
import java.net.*;

public class Chat
{
private JFrame chatFrame;
private Container container;

private JLabel addLabel;
private JTextField addTextField;
private JButton connectButton;
private JPanel connectPanel;
private JLabel stateLabel;

private JTextArea msgTextArea;
private JScrollPane msgPane;

private JTextField sendTextField;
private JButton sendButton;
private JPanel sendPanel;

private ServerSocket server;
private Socket clientSocket;
private PrintWriter pw;


public Chat()
{
chatFrame=new JFrame("聊天");
container=chatFrame.getContentPane();

addLabel=new JLabel("IP地址:");
addTextField=new JTextField(15);
connectButton=new JButton("连接");
stateLabel=new JLabel("当前状态:");
connectPanel=new JPanel();

msgTextArea=new JTextArea();
msgPane=new JScrollPane(msgTextArea);
msgTextArea.setEditable(false);
msgTextArea.setAutoscrolls(true);

sendTextField=new JTextField(50);
sendButton=new JButton("提交");
sendPanel=new JPanel();

initGUI();
}

private void initGUI()
{
connectPanel.setLayout(new FlowLayout(FlowLayout.LEFT,25,5));
connectPanel.add(addLabel);
connectPanel.add(addTextField);
connectPanel.add(connectButton);
connectPanel.add(stateLabel);

sendPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
sendPanel.add(sendTextField);
sendPanel.add(sendButton);

container.add(connectPanel,BorderLayout.NORTH);
container.add(msgPane,BorderLayout.CENTER);
container.add(sendPanel,BorderLayout.SOUTH);

chatFrame.setSize(800,600);
chatFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

ConnectListener conn=new ConnectListener();
connectButton.addActionListener(conn);
addTextField.addActionListener(conn);

SendListener send=new SendListener();
sendButton.addActionListener(send);
sendTextField.addActionListener(send);
}

public void go()
{
chatFrame.setVisible(true);
new Thread(new ConnectHost()).start();
}

private class ConnectHost implements Runnable
{
public void run()
{

while(true)
{
if (clientSocket!=null)
{
stateLabel.setText("当前状态:已连接...");
try
{
pw=new PrintWriter(clientSocket.getOutputStream(),true);
BufferedReader br=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String strResive;
while(true)
{
strResive=br.readLine();
if (!strResive.equals("null"))
msgTextArea.append(strResive+"\n");

}
}
catch(Exception e)
{
server=null;
clientSocket=null;
}

}
try
{

server=new ServerSocket(10000);
stateLabel.setText("当前状态:正在监听...");
clientSocket=server.accept();
stateLabel.setText("当前状态:已连接...");
}
catch(Exception e)
{
stateLabel.setText("当前状态:本地端口已被占用...");
}
}
}


}

private class SendListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
if (sendTextField.getText().trim().equals(""))
return;
if (clientSocket==null)
return;

pw.println(sendTextField.getText().trim());
msgTextArea.append(sendTextField.getText()+"\n");
sendTextField.setText("");
}
}

private class ConnectListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
if (addTextField.getText().trim().equals(""))
return;
String ipAddress=addTextField.getText().trim();
try
{
clientSocket=new Socket(ipAddress,10000);
stateLabel.setText("当前状态:已连接");
server.close();

}
catch(Exception e)
{
stateLabel.setText("当前状态:连接失败");
}
}
}


public static void main(String[] args)
{
new Chat().go();
}
}

#6


你把程序里的端口改成你的 就可以通信了,再有问题就是很小的问题了

#7


开源盛世嘛 呵呵!!!!希望大家有代码的都发下 大家交流交流

#8


   我自己写的聊天室没有写就放弃了,不会写啦
有时间来学习了.

#9


聊天室的实现就是Socket的问题,只要弄懂Socket,和Swing组件的事件的用法,说得白痴一点,很简单简单。。。