实现要求:编写一个程序,服务器端与客户端可以实现聊天的功能,改进后可实现多个客户端群聊功能。
服务器的代码:
package pack1;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class Server_GUI extends JPanel implements ActionListener,DocumentListener{
static Vector<Socket> v=new Vector<Socket>();
JLabel label;//标签
JButton button;//发送按钮
static JTextArea textinput,textoutput;//编辑发送,接收信息文本区
static String str=null;static boolean flag=true,flag1=false;
Server_GUI()
{
super(new FlowLayout());
textoutput=new JTextArea(24,25);
this.add(new JScrollPane(textoutput));
textoutput.getDocument().addDocumentListener(this);
/*textinput=new JTextArea(12,25);
this.add(new JScrollPane(textinput));
//为文本区对象配置文档事件监听器
textinput.getDocument().addDocumentListener(this);*/
/*button=new JButton("发送");
button.addActionListener(this);
this.add(button); */
}
//文本区监听处理
public void changedUpdate(DocumentEvent e) { }
public void insertUpdate(DocumentEvent e) { }
public void removeUpdate(DocumentEvent e) { }
//按钮监听处理
public void actionPerformed(ActionEvent e)
{
if(button==e.getSource())
{
flag=false;
}
else{}
}
public static void createAndShowGUI()
{
JFrame frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//设置内容区
frame.setContentPane(new Server_GUI());
frame.setSize(350, 530);
frame.setTitle("服务器端");
frame.setLocation(400, 300);
frame.setVisible(true);
frame.setResizable(false);//不可移动
}
public static void service(){
ServerThread thread;
Socket nextClient = null;
ServerSocket server = null;
DataInputStream in;
DataOutputStream out;
try {
server = new ServerSocket(13);
System.out.println("DayTime service started");
}
catch(IOException e1){System.out.println("正在监听,请稍等"+"\n");}
while (true) {
try {
nextClient = server.accept();
v.add(nextClient);
System.out.println(
"有客户端连上服务端, 客户端信息如下:" + nextClient.getInetAddress() + " : " + nextClient.getPort() + ".\n");
} catch (IOException e) {
System.out.println("正在等待客户端的连接");
}
if (nextClient != null) {
new ServerThread(nextClient).start();
} else {
continue;
}
}
/*try{
in=new DataInputStream(nextClient.getInputStream());
out=new DataOutputStream(nextClient.getOutputStream());
Scanner scanner=new Scanner(System.in);
//BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//BufferedReader stdin=new BufferedReader(new InputStreamReader(nextClient.getInputStream()));
textoutput.append("有客户端连上服务端, 客户端信息如下:\n" +
nextClient.getInetAddress() + " : " +nextClient.getPort() + ".\n");
while(true){
//当收到的消息不为空时
//while(in.readUTF()==null){}//当收到信息为空时等待
String s = in.readUTF();
textoutput.append(s+"\n");
//强制把光标移到最末尾,滚动条移到最末尾,显示最新聊天记录
textoutput.setCaretPosition(textoutput.getText().length());
while(flag==true){
//循环等待按钮触发
System.out.print("");
}
flag=true;
str=textinput.getText();
textinput.setText("");//清除文本区内容
//textinput.setText("消息已发送");
String send=str;
textoutput.append("服务器:"+send+"\n");
//将要输出的字符串输出
out.writeUTF("服务器:"+send);
}
}
//清除未发送的字节
finally {nextClient.close();}
}
catch (IOException e) {}*/
}
public boolean getFlag(){return flag;}
//待调用函数
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run(){
createAndShowGUI();
}
});
service();
}
}
与服务器同一个包中的ServerThread代码:
package pack1;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
class ServerThread extends Thread{
Socket socket;
DataOutputStream out=null;
DataInputStream in=null;
String s=null;
ServerThread(Socket t){
socket=t;
try{ in=new DataInputStream(socket.getInputStream());
//out=new DataOutputStream(socket.getOutputStream());
}
catch (IOException e){}
}
public void run(){
while(true){
try{
while(true){
String s = in.readUTF();
Server_GUI.textoutput.append(s+"\n");
//强制把光标移到最末尾,滚动条移到最末尾,显示最新聊天记录
Server_GUI.textoutput.setCaretPosition(Server_GUI.textoutput.getText().length());
Server_GUI.str=s;
String send=Server_GUI.str;
//Server_GUI.textoutput.append("服务器:"+send+"\n");
//将要输出的字符串输出
for(int i=0;i<Server_GUI.v.size();i++)
{
out=new DataOutputStream(Server_GUI.v.get(i).getOutputStream());
out.writeUTF(send); }
}
}
catch (IOException e){
System.out.println("客户离开");
break;
}
}
}
}
客户端的代码:
package pack1;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class Client_GUI extends JPanel implements ActionListener,DocumentListener{
JLabel label;//标签
JButton button;//发送按钮
static JTextArea textinput,textoutput;//编辑发送,接收信息文本区
static boolean flag=true;static String str=null;
static DataInputStream in;
static DataOutputStream out;
Client_GUI()
{
super(new FlowLayout());
textoutput=new JTextArea(12,25);
this.add(new JScrollPane(textoutput));
textoutput.getDocument().addDocumentListener(this);
textinput=new JTextArea(12,25);
this.add(new JScrollPane(textinput));
//为文本区对象配置文档事件监听器
textinput.getDocument().addDocumentListener(this);
button=new JButton("发送");
button.addActionListener(this);
this.add(button);
}
//文本区监听处理
public void changedUpdate(DocumentEvent e) {
}
public void insertUpdate(DocumentEvent e) {
}
public void removeUpdate(DocumentEvent e) {
}
//按钮监听处理
public void actionPerformed(ActionEvent e)
{
if(button==e.getSource())
{
str=textinput.getText();
textinput.setText("");
String send = str;
try {
out.writeUTF("克莱汤普森:" + send);
} catch (IOException e1) {
e1.printStackTrace();
}
}
else{}
}
public static void createAndShowGUI()
{
JFrame frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//设置内容区
frame.setContentPane(new Client_GUI());
frame.setSize(350, 530);
frame.setTitle("克莱汤普森");
frame.setLocation(900, 300);
frame.setVisible(true);
frame.setResizable(false);//不可移动
}
public static void client(){
String hostname;
hostname="localhost";//设定为本机,此地址为 获取目的精准时间的 地址
try{
Socket theSocket=new Socket(hostname,13);
try{
in=new DataInputStream(theSocket.getInputStream());
out=new DataOutputStream(theSocket.getOutputStream());
Scanner scanner=new Scanner(System.in);
//textoutput.append("已连接上服务器,开始对话吧!");
while(true){
String accpet=null;
while((accpet = in.readUTF()).length()>0){
textoutput.append(accpet+"\n");
//强制把光标移到最末尾,滚动条移到最末尾,显示最新聊天记录 textoutput.setCaretPosition(textoutput.getText().length());
}
}
}
finally{theSocket.close();}
}
catch (IOException e) {
}
}
//待调用函数
public static void main(String[] args) {
// TODO Auto-generated method stub
EventQueue.invokeLater(new Runnable(){
public void run(){
createAndShowGUI();
}
}); client();
}
}
第一篇博客,欢迎各位大佬指正!(逃