IT十八掌作业_java基础第十六天_GUI/socket
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IT十八掌作业_java基础第十六天_GUI/socket相关的知识,希望对你有一定的参考价值。
参照视频,编写出聊天程序。
知识点分析:
Socket + GUI + IO = 简版QQ
------------------------------
1.GUI
2.Socket
ServerSocket : port + accept
Socket sock = accept();
//更新窗口
//接收client的数据
new Thread(){
run(){
sock..getInputStream();
....
//更新窗口
}
}.start()
3.在分线程中完成ServerSocket推送消息给所有客户端。
List<OutputStream> ... = ;
4.推送联系人列表给所有客户端。
-------------------------------------------------------------------------------------------
package com.it18zhang.QQDemo;
public class App {
public static void main(String[] args) {
//创建窗口
MyWindow w = new MyWindow();
//消息服务器
MessageServer server = new MessageServer(w);
//启动消息服务器
server.start(1234);
}
}
package com.it18zhang.QQDemo;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class ClientDemo {
public static void main(String[] args) throws Exception {
Socket s = new Socket("localhost",1234);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream(),"gbk"));
bw.write("TCP hello!");
s.close();
}
}
package com.it18zhang.QQDemo;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
public class MyWindow extends JFrame {
private static final long serialVersionUID = 6142786986925220872L;
// 历史记录
private JTextArea taHistory;
// 发送内容
private JTextArea taContent;
// 发送按钮
private JButton btnSend;
// 联系人列表
private JList listContacts;
private JTable table;
// 初始化窗体
public MyWindow() {
ini();
}
// 初始化动作
private void ini() {
// 设置边界大小,位置
this.setSize(600, 400);
this.setLocation(200, 200);
// 设置为绝对布局
this.setLayout(null);
// 设置联系人表格
table = new JTable();
table.setBounds(500, 0, 100, 400);
this.add(table);
// 设置聊天记录区
taHistory = new JTextArea();
taHistory.setEditable(false);
taHistory.setBounds(0, 0, 480, 300);
this.add(taHistory);
this.setVisible(true);
// 添加监听事件
this.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(-1);
}
});
}
/**
* 刷新联系人
*/
public void refreshContacts(final List<String> clients){
Set<String> set = new HashSet<String>(clients);
final List<String> newclients = new ArrayList<String>(set);
TableModel dataModel = new AbstractTableModel() {
public Object getValueAt(int row, int col) {
return newclients.get(row);
}
public int getRowCount() {
return newclients.size();
}
public int getColumnCount() {
return 1;
}
};
table.setModel(dataModel);
}
/**
* 更新聊天记录
*/
public void updateHistory(String addr, String line) {
//原文
String old = taHistory.getText();
StringBuilder builder = new StringBuilder();
builder.append(old);
builder.append("\r\n");
builder.append(addr);
builder.append("\r\n");
builder.append(line);
builder.append("\r\n");
//更新聊天区域
taHistory.setText(builder.toString());
}
}
package com.it18zhang.QQDemo;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
/**
* 消息服务器
*/
public class MessageServer {
//定义客户端集合,
private List<String> clients = new ArrayList<String>();
private MyWindow window;
public MessageServer(MyWindow window) {
this.window = window;
}
//启动服务器
public void start(int port){
try {
ServerSocket ss = new ServerSocket(port);
System.out.println("服务器启动了");
InetAddress remAddr ;
int remPort;
while(true){
final Socket sock = ss.accept();
System.out.println(SocketUtil.getAddr(sock)+" : connected");
new MessageReceiverThread(window,sock).start();
remAddr = sock.getInetAddress();
remPort = sock.getPort();
//添加客户端对象
clients.add(SocketUtil.getAddr(sock));
//刷新列表
window.refreshContacts(clients);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.it18zhang.QQDemo;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
/**
* 消息接收线程
*/
public class MessageReceiverThread extends Thread {
private MyWindow window ;
private Socket sock ;
public MessageReceiverThread(MyWindow window, Socket sock) {
this.window = window;
this.sock = sock;
}
public void run(){
while(true){
try {
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream(), "gbk"));
String line = null;
while((line = br.readLine()) != null){
window.updateHistory(SocketUtil.getAddr(sock),line); //更新历史列表
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
package com.it18zhang.QQDemo;
import java.net.Socket;
public class SocketUtil {
/**
* 返回地址串
*/
public static String getAddr(Socket sock){
String ip = sock.getInetAddress().getHostAddress();
String ip0 = ip.substring(ip.lastIndexOf(".")+1);
return ip0+":"+sock.getPort();
}
}
本文出自 “菜鸟成就数据之路” 博客,转载请与作者联系!
以上是关于IT十八掌作业_java基础第十六天_GUI/socket的主要内容,如果未能解决你的问题,请参考以下文章