码迷,mamicode.com
首页 > 编程语言 > 详细

使用 Java 创建聊天客户端-2

时间:2019-11-27 12:16:22      阅读:62      评论:0      收藏:0      [点我收藏+]

标签:绑定   edr   group   else   按钮   接收   nts   客户端   xtend   

1.项目截图

技术图片

 

 

java聊天核心代码:

MyJavaChatClient

====================================================================================================================================

ChatManager.java

package com.nantian.javachatclient.main;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import com.nantian.javachatclient.view.MainWindow;

public class ChatManager {
//界面中只能向chatManager发送数据,那么接收到数据后怎样放到界面上呢?
//需要对MainWindow有个引用,并为它实现setWindow方法
MainWindow window;
//创建本地socket对象
Socket socket;
//声明ip
String IP;
//输入流
BufferedReader reader;
//输出流
PrintWriter writer;

public void setWindow(MainWindow window) {
this.window=window;
//传递之后
window.appendText("文本框已经和ChatManager绑定了!");
}
//将类单例化的步骤就是讲他的构造方法变成private
//ChatManager就会有唯一的实例
private ChatManager() {}
private static final ChatManager instance=new ChatManager();
public static ChatManager getChatManager() {
return instance;
}
//具体实现连接服务器的操作
public void connect(String ip) {
this.IP=ip;
//呼叫连接的时候需要创建新的线程
new Thread() {
//覆盖thread的run方法
@Override
public void run() {
//核心内容处理方法
try {
socket=new Socket(IP,12345);
//将OutPutStream包装成OutPutStreamWriter,然后再包装成PrintWriter
writer=new PrintWriter(
new OutputStreamWriter(
socket.getOutputStream()));
//读取的输入流
reader=new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
//循环监听当前输入流是否有数据
//本地创建字符串
String line;
//首先让line读取一行数据
while((line=reader.readLine())!=null) {
//输出到界面当中
window.appendText("收到:"+line);
}
//关闭流
writer.close();
reader.close();
//关闭流之后赋值为空
writer=null;
reader=null;
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}

//"发送"按钮发送内容函数
public void send(String out) {
//点击"发送"按钮,需要首先判断writer是否为空,不为空继续
if (writer!=null) {
//服务器没有提示在控制台输出内容,这是因为没有添加\n,这时flush才可以将这行内容输出
writer.write(out+"\n");
//强制刷新输出
writer.flush();
}else {
window.appendText("当前的连接已经中断!!!");
}
}


}

====================================================================================================================================

StartClient.java

package com.nantian.javachatclient.main;

import java.awt.EventQueue;

import com.nantian.javachatclient.view.MainWindow;

public class StartClient {
/**
* 将窗体主方法放到了这里
* @param args
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow frame = new MainWindow();
frame.setVisible(true);
//创建window的时候,对MainWindow有个引用
ChatManager.getChatManager().setWindow(frame);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

}

===================================================================================================================================

MainWindow.java

package com.nantian.javachatclient.view;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import com.nantian.javachatclient.main.ChatManager;

import javax.swing.JTextArea;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class MainWindow extends JFrame {

/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
//文本控件声明到类中,让他作为类的变量
JTextArea txt;
private JTextField IP;
private JTextField send;

/**
* Create the frame.
*/
public MainWindow() {
//因为每次创建客户端会把它压在下面,所以设置如下
setAlwaysOnTop(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);

txt = new JTextArea();
txt.setText("Ready...");

IP = new JTextField();
IP.setText("127.0.0.1");
IP.setColumns(10);

JButton button = new JButton("连接到服务器");
button.addMouseListener(new MouseAdapter() {
//mouse-->clicked自动创建的代码
@Override
public void mouseClicked(MouseEvent e) {
//为"连接到服务器"按钮添加动作
//使用函数把它和这个按钮的监听事件绑定起来
ChatManager.getChatManager().connect(IP.getText());
}
});

send = new JTextField();
send.setText("你好!");
send.setColumns(10);

JButton button_1 = new JButton("发送");
button_1.addMouseListener(new MouseAdapter() {
//为"发送"按钮添加动作
@Override
public void mouseClicked(MouseEvent e) {
//当前文本发送呢内容
ChatManager.getChatManager().send(send.getText());
appendText("我说:"+send.getText());
//发送出去后,需要将当前文本框清空
send.setText("");
}
});
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup()
.addGroup(gl_contentPane.createParallelGroup(Alignment.TRAILING)
.addComponent(txt, GroupLayout.DEFAULT_SIZE, 414, Short.MAX_VALUE)
.addGroup(Alignment.LEADING, gl_contentPane.createSequentialGroup()
.addComponent(IP)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(button))
.addGroup(gl_contentPane.createSequentialGroup()
.addComponent(send, GroupLayout.DEFAULT_SIZE, 295, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(button_1, GroupLayout.PREFERRED_SIZE, 129, GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(IP, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(button))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(txt, GroupLayout.DEFAULT_SIZE, 193, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(send, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(button_1)))
);
contentPane.setLayout(gl_contentPane);
}

public void appendText(String in) {
txt.append("\n"+in);
}
}

====================================================================================================================================

TestMyServerSocket代码在前面项目

先启动服务端:

技术图片

 

后启动客户端:

技术图片

 

 技术图片

 

 断开连接:

技术图片

 

 

 

使用 Java 创建聊天客户端-2

标签:绑定   edr   group   else   按钮   接收   nts   客户端   xtend   

原文地址:https://www.cnblogs.com/curedfisher/p/11941105.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!