我在我的服务器窗体上有一个JTable,它是由MySQL数据库填充的,在构造函数中编码:
String sql = "SELECT * from fiekorari";
try{
pst=conn.prepareStatement(sql);
res=pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(res));
pst.close();
res.close();
} catch (SQLException e1){
e1.printStackTrace();
}
使用TCP连接在main上建立连接,服务器端:
public class Serveri extends JFrame {
private JPanel contentPane;
static ServerSocket ss;
static Socket s;
static DataInputStream din;
static DataOutputStream dout;
private JTextField txtMesazhi;
private static JTextArea txtA;
static Connection conn=null;
static ResultSet res= null;
static PreparedStatement pst = null;
private Object id;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Serveri frame = new Serveri();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
SqlConn.getConnection();
String msgin="";
try
{
ss=new ServerSocket(1201);
s=ss.accept();
din=new DataInputStream(s.getInputStream());
dout=new DataOutputStream(s.getOutputStream()); //code continues with chat programming
我想将数据从服务器端的JTable发送到客户端的JTable,我不确定这是不是正确的方法,但我的任务是让服务器读取数据库数据并将其发送到客户端。
下面是客户端的代码,它通过TCP建立一个用于聊天的连接,但现在我必须添加一个表,它通过套接字从服务器表中读取数据:
public class Klienti extends JFrame {
private JPanel contentPane;
private JTextField txtMesazhi;
private static JTextArea txtShfaq1;
static Socket s;
static DataInputStream din;
static DataOutputStream dout;
private JButton btnNewButton;
public static String sql1;
private JTable table;
private JTextField txtEmri;
private JTextField txtMbiemri;
private JTextField txtOra;
static Connection conn=null;
static ResultSet res= null;
static PreparedStatement pst = null;
private Pattern pattern;
private Matcher matcher;
private String loc;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Klienti frame = new Klienti();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
//SqlConn.getConnection();
try
{
s=new Socket("localhost",1201);
din=new DataInputStream(s.getInputStream());
dout=new DataOutputStream(s.getOutputStream());
//code in constructor Client side which sends text message to Server through sockets:
dout.writeUTF(msgout);
txtShfaq1.setText(txtShfaq1.getText().trim()+"\nJu:\t"+msgout);
txt.setText("");
发布于 2018-06-02 07:55:39
不,您不应该将JTable从服务器发送到客户端。实际上,服务器不应该有任何swing组件。它应该只根据请求获取数据,并以适当的格式发送数据,而不是包装在JTable中。
另外一点,尽量不要做纯socket通信。使用更高级别的协议,如HTTP。服务器可以运行http web服务并且可以使数据以json、xml格式可用。
客户端可以使用许多可用的http客户端中的任何一个来从服务器获取数据。这些库已经解决了许多套接字连接问题。
https://stackoverflow.com/questions/50644140
复制相似问题