Socket类,想要实现两个窗口的C-S通信,该怎么做

Ssmj96 2016-11-28 04:22:50
import java.awt.BorderLayout;
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.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;


public class CSTEST {

public static void main(String args[]){
JFrame f1=new JFrame("服务器");
f1.setBounds(100,100,500,500);
JTextArea area1=new JTextArea();
JPanel p1=new JPanel();
JButton button1=new JButton("发送");
button1.addActionListener(new Mishu(area1));
p1.add(button1);
f1.add(area1);
f1.add(p1,BorderLayout.SOUTH);
f1.setVisible(true);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JFrame f2=new JFrame("客户端");
f2.setBounds(100,100,500,500);
JTextArea area2=new JTextArea();
JPanel p2=new JPanel();
JButton button2=new JButton("发送");
p2.add(button2);
f2.add(area2);
f2.add(p2,BorderLayout.SOUTH);
f2.setVisible(true);
f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button2.addActionListener(new Mishu2(area2));
}
}
class Mishu implements ActionListener{
JTextArea taa;
Mishu(JTextArea ta){
taa=ta;
}
public void actionPerformed(ActionEvent e){
ServerSocket se=null;
Socket soc=null;
DataInputStream in=null;
DataOutputStream out=null;
try {
se=new ServerSocket(2010);

} catch (IOException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
try {
//taa.append("等待客户呼叫 !");
soc=se.accept();
out=new DataOutputStream(soc.getOutputStream());
in=new DataInputStream(soc.getInputStream());
String s=in.readUTF();
taa.append(s);
out.writeUTF(taa.getText());
} catch (IOException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
taa.append("客户已断开");
}
}
}

class Mishu2 implements ActionListener{
JTextArea taa;
Mishu2(JTextArea ta){
taa=ta;
}
public void actionPerformed(ActionEvent e){

Socket mysocket;
DataInputStream in=null;
DataOutputStream out=null;
try {
String ip=InetAddress.getLocalHost().getHostAddress();
mysocket=new Socket(ip,2010);
in =new DataInputStream(mysocket.getInputStream());
out=new DataOutputStream(mysocket.getOutputStream());
out.writeUTF(taa.getText());
String s=in.readUTF();
taa.append(s);
} catch (IOException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}

}
}
...全文
207 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
Ssmj96 2016-11-29
  • 打赏
  • 举报
回复
有没有大神能告诉我错在哪啊
Ssmj96 2016-11-28
  • 打赏
  • 举报
回复
我想问,为啥我那些写不行啊?
computerclass 2016-11-28
  • 打赏
  • 举报
回复
package Chat; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; public class ClientFrame{ private PrintWriter pw; private JFrame frame; private JPanel pane_buttom; private JSplitPane pane_center; //锟斤拷示锟斤拷锟捷碉拷锟侥憋拷锟斤拷锟斤拷锟斤拷锟斤拷锟捷碉拷锟侥憋拷锟斤拷,锟斤拷锟斤拷锟斤拷锟捷帮拷钮 private JScrollPane pane_showWindow; private JScrollPane pane_inputWindow; private JTextArea area_showWindow; private JTextArea area_inputWindow; private JButton btn_send; private Dimension dimension;//锟斤拷锟斤拷锟斤拷锟斤拷area_showWindow锟斤拷锟斤拷锟斤拷锟侥达拷小 //锟斤拷始锟斤拷 public ClientFrame() { frame = new JFrame(); pane_buttom = new JPanel(); pane_showWindow = new JScrollPane(); pane_inputWindow = new JScrollPane(); area_showWindow = new JTextArea(); area_inputWindow = new JTextArea(); pane_center = new JSplitPane(JSplitPane.VERTICAL_SPLIT, false, pane_showWindow, pane_inputWindow); btn_send = new JButton("锟斤拷锟斤拷"); dimension = new Dimension(50, 300); } //锟斤拷锟矫凤拷锟斤拷锟斤拷示锟斤拷锟斤拷 public void showFrame(){ initFrame(); initChatTextArea(); initButton(); btn_send(); socket(); } //锟斤拷锟斤拷锟斤拷 public void initFrame(){ frame.setTitle("锟酵伙拷锟斤拷"); int width = (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth(); int height = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight(); frame.setBounds(width / 2, height / 2, 400, 450); frame.setVisible(true); } //锟斤拷锟斤拷锟斤拷示锟侥憋拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷谋锟斤拷锟? private void initChatTextArea(){ //取锟斤拷锟斤拷图锟斤拷锟斤拷 pane_showWindow.getViewport().add(area_showWindow); pane_inputWindow.getViewport().add(area_inputWindow); //锟斤拷锟斤拷示锟侥憋拷锟斤拷锟斤拷锟斤拷为锟斤拷锟缴编辑 area_showWindow.setEditable(false); //锟斤拷锟斤拷锟斤拷示锟侥憋拷锟斤拷锟斤拷锟斤拷锟斤拷拇锟叫? pane_showWindow.setMinimumSize(dimension); frame.add(pane_center, BorderLayout.CENTER); } //锟斤拷锟斤拷锟侥硷拷锟斤拷锟斤拷锟斤拷锟斤拷锟捷帮拷钮 public void initButton(){ pane_buttom.add(btn_send); frame.add(pane_buttom, BorderLayout.SOUTH); } private void btn_send(){ btn_send.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String info = area_inputWindow.getText(); area_showWindow.append("锟酵伙拷锟剿o拷 "+info+"\r\n"); pw.println(info); area_inputWindow.setText(""); } }); } private void socket(){ try { Socket s = new Socket("127.0.0.1",9000); InputStreamReader isr=new InputStreamReader(s.getInputStream()); BufferedReader br=new BufferedReader(isr); pw=new PrintWriter(s.getOutputStream(),true); while(true){ //锟斤拷停锟截讹拷取锟接凤拷锟斤拷锟斤拷锟剿凤拷锟斤拷锟斤拷锟斤拷息 String info=br.readLine(); area_showWindow.append("锟斤拷锟斤拷耍锟?"+info+"\r\n"); } } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { ClientFrame chat = new ClientFrame(); chat.showFrame(); } }
computerclass 2016-11-28
  • 打赏
  • 举报
回复
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.abc.socketdemo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; /** * http://bbs.csdn.net/topics/340012112 * * @author Administrator */ public class ServerJFrame extends javax.swing.JFrame implements Runnable { Thread current; PrintWriter pw = null; ServerSocket serverSocket; int port = 9000; // private PrintWriter pw; /** * Creates new form ServerJFrame */ public ServerJFrame() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); showWindow = new javax.swing.JTextArea(); jScrollPane2 = new javax.swing.JScrollPane(); inputWindow = new javax.swing.JTextArea(); sendContent = new javax.swing.JButton(); startService = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); showWindow.setColumns(20); showWindow.setRows(5); showWindow.setName("showWindow"); // NOI18N jScrollPane1.setViewportView(showWindow); inputWindow.setColumns(20); inputWindow.setRows(5); inputWindow.setName(""); // NOI18N jScrollPane2.setViewportView(inputWindow); sendContent.setText("鍙戦€?); sendContent.setName("sendContent"); // NOI18N sendContent.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sendContentActionPerformed(evt); } }); startService.setLabel("杩炴帴"); startService.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { startServiceActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(startService) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(sendContent))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(sendContent) .addComponent(startService)) .addGap(27, 27, 27)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void sendContentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendContentActionPerformed // TODO add your handling code here: String info = inputWindow.getText(); showWindow.append("鏈嶅姟绔細" + info + "\r\n"); pw.println(info); inputWindow.setText(""); }//GEN-LAST:event_sendContentActionPerformed private void startServiceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startServiceActionPerformed try { // TODO add your handling code here: serverSocket = new ServerSocket(port); } catch (IOException ex) { Logger.getLogger(ServerJFrame.class.getName()).log(Level.SEVERE, null, ex); } if (current == null || !current.isAlive()) { current = new Thread(this); current.start(); } }//GEN-LAST:event_startServiceActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ServerJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ServerJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ServerJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ServerJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ServerJFrame().setVisible(true); } }); } @Override public void run() { Socket socket; try { System.out.println("runn......."); //鐩戝惉绔彛锛屽鏋滄湁鐢ㄦ埛鐧婚檰灏卞缓绔嬭繛鎺? while (true) { socket = serverSocket.accept(); new ServerThread(socket).start(); //鐒跺悗鍦╯erverThread鐨勬瀯閫犳柟娉曢噷鍚姩绾跨▼this.start(); } } catch (Exception e) { System.err.println("Not listening......" + e); } //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public class ServerThread extends Thread { private Socket socket; private String str; private String msg; public ServerThread(Socket socket) { this.socket = socket; } public void run() { BufferedReader br = null; //PrintWriter pw = null; try { str = "New connection accepted " + socket.getInetAddress() + ":" + socket.getPort(); System.out.println(str); br = new BufferedReader(new InputStreamReader(socket.getInputStream())); pw = new PrintWriter(socket.getOutputStream(), true); while ((msg = br.readLine()) != null) { msg = socket.getInetAddress() + ":" + socket.getPort() + "say:" + msg; //System.out.println(msg); showWindow.setText(msg); pw.println(msg); if (msg.equals("bye")) { break; } } } catch (IOException ex) { Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex); } finally { try { br.close(); } catch (IOException ex) { Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex); } } } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextArea inputWindow; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JButton sendContent; private javax.swing.JTextArea showWindow; private javax.swing.JButton startService; // End of variables declaration//GEN-END:variables }
computerclass 2016-11-28
  • 打赏
  • 举报
回复
至少得两个类

50,530

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧