天气: 晴朗

Java的客户端与服务器,客户端可以发信息,想加一个让服务器也能发信息?
package Other;import java.awt.Container;import java.awt.FlowLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.IOException;import java.io.PrintWriter;import java.io.Writer;import java.net.InetAddress;import java.net.InetSocketAddress;import java.net.ServerSocket;import java.net.Socket;import java.net.SocketAddress;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextArea;import javax.swing.JTextField;public class Server extends JFrame { private JPanel p1, p2, p4, p5, p6; private JLabel lb1, lb2, lb3, lb4; private Container container; private JTextField t1, t2; private static JTextArea ta; private JButton bt; public Server() { this.setTitle; container = this.getContentPane(); container.setLayout(new FlowLayout(FlowLayout.LEFT)); lb1 = new JLabel(“服务器启动面板”); lb2 = new JLabel(“服务器主机名:”); lb3 = new JLabel; lb4 = new JLabel(“服务器收到客户机消息面板”); bt = new JButton; bt.addActionListener(new btActionListener; t1 = new JTextField; t2 = new JTextField; ta = new JTextArea;// ta.addActionListener(new taActionListener; p1 = new JPanel(); p2 = new JPanel(); p4 = new JPanel(); p5 = new JPanel(); p6 = new JPanel(); p1.add; container.add; p2.add; p2.add; p2.add; p2.add; p2.add; container.add; p4.add; container.add; p5.add; p6.add; container.add; this.setSize; this.setVisible; this.setResizable; } private ServerSocket listenSocket =null; private Socket toClientSocket = null; private BufferedReader in; private PrintWriter out; public static int clientCounts = 0; public class taActionListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { } } public class btActionListener implements ActionListener { public void actionPerformed(ActionEvent arg0) { try { bt.setEnabled; String hostName = t1.getText(); int hostPort = Integer.parseInt(t2.getText; SocketAddress serverAddr = new InetSocketAddress( InetAddress.getByName,hostPort); listenSocket = new ServerSocket(); listenSocket.bind(serverAddr); ta.append(“服务器开始等待客户机连接…n”); } catch (Exception e) {} //创建匿名线程,创建响应客户机的会话线程 new Thread(new Runnable() { @Override public void run() { try { while { // 处理客户机连接 toClientSocket = listenSocket.accept(); // 侦听并接受客户机连接 clientCounts++; ta.append(toClientSocket.getRemoteSocketAddress() + “客户机编号” + clientCounts + “会话开始…n”); // 创建客户线程clientThread,实现一客户一线程 Thread clientThread = new ClientThread(toClientSocket, clientCounts); clientThread.start(); }//end while } catch (IOException e) { JOptionPane.showMessageDialog(null, e.getMessage(), “错误提示”, JOptionPane.ERROR_MESSAGE); return; } }//end run.start(); } } private void formWindowClosing (java.awt.event.WindowEvent evt){ try { if(in != null)in.close(); if(out != null)out.close(); if (listenSocket != null)listenSocket.close(); if (toClientSocket != null)toClientSocket.close(); } catch (Exception e) {} } public static void main(String[] args) { new Server(); } public static JTextArea getScreen() { return ta; }}服务器代码:package Other;import java.awt.Container;import java.awt.FlowLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.net.InetAddress;import java.net.InetSocketAddress;import java.net.Socket;import java.net.SocketAddress;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.JTextArea;import javax.swing.JTextField;public class Client extends JFrame { private JPanel p1, p2, p3, p5, p6, p7; private JLabel lb1, lb2, lb3, lb4, lb5; private Container container; private JTextField t1, t2, t3; private static JTextArea ta; private JButton bt1, bt2; public Client(){ this.setTitle; container = this.getContentPane(); container.setLayout(new FlowLayout(FlowLayout.LEFT)); lb1 = new JLabel; lb2 = new JLabel(“服务器主机名:”); lb3 = new JLabel; lb4 = new JLabel; lb5 = new JLabel(“服务器Echo消息面板”); bt1 = new JButton; bt2 = new JButton; bt1.addActionListener(new bt1ActionListener; bt2.addActionListener(new bt2ActionListener; t1 = new JTextField; t2 = new JTextField; t3 = new JTextField; ta = new JTextArea; p1 = new JPanel(); p2 = new JPanel(); p3 = new JPanel(); p5 = new JPanel(); p6 = new JPanel(); p7 = new JPanel(); p1.add; container.add; p2.add; p2.add; p2.add; p2.add; p2.add; container.add; p3.add; p3.add; p3.add; container.add; p5.add; container.add; p6.add; p7.add; container.add; this.setSize; this.setVisible; this.setResizable; } private Socket clientSocket = null; private BufferedReader in; private PrintWriter out; public class bt1ActionListener implements ActionListener { public void actionPerformed(ActionEvent arg0) { try { bt1.setEnabled; String remoteName = t1.getText(); int remotePort = Integer.parseInt(t2.getText; SocketAddress remoteAddr = new InetSocketAddress( InetAddress.getByName(remoteName),remotePort); clientSocket = new Socket(); clientSocket.connect(remoteAddr); ta.append(“连接服务器成功,会话开始…n”); out = new PrintWriter(new OutputStreamWriter( clientSocket.getOutputStream(),”UTF-8″),true); in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream(),”UTF-8″)); } catch (Exception e) { JOptionPane.showConfirmDialog(null, e.getMessage(), “连接错误”,JOptionPane.ERROR_MESSAGE); return; } } } public class bt2ActionListener implements ActionListener { public void actionPerformed(ActionEvent arg0) { if(clientSocket == null){ JOptionPane.showMessageDialog(null, “请先检查服务器连接情况。n确保客户及连接服务器!”, “错误提示”, JOptionPane.ERROR_MESSAGE); return; } String outStr = t3.getText(); if(outStr.length{ JOptionPane.showMessageDialog(null, “请输入发送消息!”, “提示”, JOptionPane.ERROR_MESSAGE); return; } out.println; t3.setText; try { String inStr; inStr = in.readLine(); ta.append(“Echo:” + inStr + “n”); } catch (Exception e) { JOptionPane.showMessageDialog(null, “客户机接收消息错误!”, “错误提示”, JOptionPane.ERROR_MESSAGE); return; } } } private void formWindowClosing(java.awt.event.WindowEvent evt){ try { if(in != null)in.close(); if(out != null)out.close(); if(clientSocket != null)clientSocket.close(); } catch (Exception e) {} } public static void main(String[] args) { new Client(); }}多线程:package Other;import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWriter;import java.net.Socket;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;public class ClientThread extends Thread { private Socket toClientSocket = null; private BufferedReader in; private PrintWriter out; public static int clientCounts = 0; public ClientThread(Socket toClientSocket,int clientCounts){ this.toClientSocket = toClientSocket; this.clientCounts = clientCounts; } @Override public void run() { try { in = new BufferedReader( new InputStreamReader(toClientSocket.getInputStream(),”UTF-8″)); out = new PrintWriter( new OutputStreamWriter(toClientSocket.getOutputStream(),”UTF-8″),true); //根据服务器协议,在网络流上进行读写操作 String recvStr; while((recvStr = in.readLine != null){ //客户机关闭,反复等待 System.out.println; Date date = new Date(); //和接受客户机消息 DateFormat format = new SimpleDateFormat(“yyyy-mm-dd hh:mm:ss”); String time = format.format; //解析并显示收到的信息 Server.getScreen().append(toClientSocket.getRemoteSocketAddress() + “客户机编号:” + clientCounts + “消息:” + recvStr + “:” + time + “n”); //按照Echo协议原封不动会送消息 out.println(toClientSocket.getLocalAddress() + “客户机编号:” + clientCounts + “Echo消息:” + recvStr + “:” + time); }//end while Server.clientCounts–; //远程客户机断开,释放资源 if(in != null)in.close(); if(out != null)out.close(); if (toClientSocket != null)toClientSocket.close(); } catch (Exception e) {} }//end run}//end class

1.

心情: 平静

package CLASS16.bin.com.GridLayout;

代码如下,很简单,只是向服务器发送请求,得到一个XML流然后解析。。使用代理是因为公司限制的原因。

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JSplitPane;

澳门新葡萄京官网首页 1

public class Swing extends JFrame{
JSplitPane jsp;
JList jli;
JLabel jla;
public static void main(String[] args) {
Swing a=new Swing();
}

package com.searchWord;

public Swing(){
澳门新葡萄京官网首页,String[] sh={“boy”,”gril”,”brod”};
jli=new JList(sh);
jla=new JLabel(new ImageIcon(“images/1.jpg”));
jsp=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,jli,jla);
//设置布局管理器
//添加组件
this.add(jsp);

import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//可以伸缩
jsp.setOneTouchExpandable(true);
// this.setBounds(200, 200, 400, 300);
this.setLocation(200, 200);
this.setSize(400, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.setVisible(true);

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

}

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

}

/**
 * @author shuai.yang
 *
 */
public class SearchWord extends JFrame. implements ActionListener {

实现效果  如下:

 /**
  * default ID create by Eclipse
  */
 private static final long serialVersionUID = -7624995201710742391L;
 
 private static final String searchURL = “=”;
 
 private static final String errorMsg_NoFound = “No found”;
 
 private static final String sampleTitle = “sample:”;
 
 private static final String proxyURL = “gzcpx1001.gdnchina.com”;
 
 private static final String formTitle = “SFA中英文查询器-测试版本V1.0”;

澳门新葡萄京官网首页 2

 private static final String alertMsg = “请输入要查询的内容!”;
 
 private JTextArea r = new JTextArea(15, 26);

2.

 private JButton b = new JButton();

package CLASS16.bin.com.GridLayout;

 private JTextField t = new JTextField();
 
 private JTextField proxyTxt = new JTextField();

import java.awt.BorderLayout;

 private JCheckBox proxyCBox = new JCheckBox();
 
 /**
  * default construct
  *
  */
 public SearchWord() {
  initForm();
 }

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

 /**
  * init JFrame
  *
  */
 private void initForm() {
  this.add(initPanel());
  this.setTitle(formTitle);
  this.setSize(350, 400);
  Toolkit t = Toolkit.getDefaultToolkit();
  this.setLocation(
    (int) (t.getScreenSize().getWidth() – this.getWidth()) / 2,
    (int) (t.getScreenSize().getHeight() – this.getHeight()) / 2);
  this.setResizable(false);
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setVisible(true);
  
 }

public class QQsay extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
JTextArea jte=null;
JScrollPane jsc=null;
JPanel jpa=null;
JComboBox jco=null;
JTextField jtf=null;
JButton jbu=null;
public static void main(String[] args) {
@SuppressWarnings(“unused”)
QQsay qq=new QQsay();

 /**
  * initPanel
  *
  * @return JPanel
  */
 private JPanel initPanel() {
  JPanel p = new JPanel();
  JPanel pInput = new JPanel();
  JPanel copyRight = new JPanel();
  pInput.add(initText(), BorderLayout.CENTER);
  pInput.add(initButton(), BorderLayout.CENTER);
  JScrollPane pResult = new JScrollPane(initResultPanel(“”));
  copyRight.add(initProxyTxt(),BorderLayout.CENTER);
  copyRight.add(initProxyCheckBox(),BorderLayout.CENTER);
  p.add(pInput, BorderLayout.NORTH);
  p.add(pResult, BorderLayout.CENTER);
  p.add(copyRight, BorderLayout.CENTER);
  return p;
 }

}
//构造
public QQsay(){
jte=new JTextArea();
//多行文本滚动条
jsc=new JScrollPane(jte);
jpa=new JPanel();
String []sh={“张三”,”王二”};
jco=new JComboBox(sh);
jtf=new JTextField(10);
jbu=new JButton(“发送”);
//设置布局

 /**
  * initProxyCheckBox
  *
  * @return
  */
 private JCheckBox initProxyCheckBox() {
  proxyCBox.setText(“使用代理”);
  proxyCBox.setSelected(true);
  proxyCBox.addItemListener(new ItemListener(){
   public void itemStateChanged(ItemEvent e) {
    if (e.getStateChange() == ItemEvent.SELECTED)
     proxyTxt.setEditable(false);
    if (e.getStateChange() == ItemEvent.DESELECTED)
     proxyTxt.setEditable(true); 
   }});
  return proxyCBox;
 }

//添加组件
jpa.add(jco);
jpa.add(jtf);
jpa.add(jbu);

 /**
  * initProxyTxt
  *
  * @return
  */
 private JTextField initProxyTxt() {
  proxyTxt.setColumns(18);
  proxyTxt.setText(proxyURL);
  proxyTxt.setEditable(false);
  return proxyTxt;
 }
 /**
  * initButton
  *
  * @return JButton
  */
 private JButton initButton() {
  b.setText(“查询”);
  b.addActionListener(this);
  return b;
 }

//加入到JFrmare
this.add(jsc);
this.add(jpa,BorderLayout.SOUTH);
//属性

 /**
  * initText for input
  *
  * @return JTextField
  */
 private JTextField initText() {
  t.setColumns(20);
  t.addKeyListener(new KeyAdapter(){//添加直接回车查询事件
   public void keyReleased(KeyEvent e) {
    if(e.getKeyCode() == 10){
     actionPerformed(null);
    }
   }
  });
  return t;
 }

this.setSize(300,200);
this.setLocation(200, 200);
this.setIconImage((new ImageIcon(“images/qq.jpg”)).getImage());
this.setTitle(“腾讯qq”);
//退出程序
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

 /**
  * initResultPanel for display result
  *
  * @param result
  * @return JTextArea
  */
 private JTextArea initResultPanel(String result) {
  r.setAutoscrolls(true);
  r.setText(result);
  r.setEditable(false);
  r.setLineWrap(true);
  return r;
 }

this.setVisible(true);

 /**
  * JButtion click
  */
 public void actionPerformed(ActionEvent arg0) {
  if (“”.equals(t.getText().trim())) {
   JOptionPane.showMessageDialog(this, alertMsg);
  } else {
   this.setTitle(formTitle);
   initResultPanel(getSearchResult());
  }
 }

}

 /**
  * getSearchResult
  *
  * @return searchResult
  */
 private String getSearchResult() {
  StringBuffer result = new StringBuffer();
  try {
   // FileInputStream in = new FileInputStream(new File(“d:/a.xml”));
   InputStream in = getURLInputSteam(searchURL +
t.getText().replaceAll(” “,””));
   Document doc = null;
   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
   DocumentBuilder db = dbf.newDocumentBuilder();
   doc = db.parse(in);
   NodeList nl = doc.getElementsByTagName(“dict”);
   for (int i = 0; i < nl.getLength(); i++) {
    Element e = (Element) nl.item(i);
    if(null == e.getElementsByTagName(“def”).item(0).getFirstChild()){
     result.append(errorMsg_NoFound).append(“n”);
    }else{
     String explainDef =
e.getElementsByTagName(“def”).item(0).getFirstChild().getNodeValue();
     result.append(explainDef).append(“n”);
     NodeList nlSample = doc.getElementsByTagName(“sent”);
     for (int j = 0; j < nlSample.getLength(); j++) {
      if (j == 0) result.append(“n”+ sampleTitle + “n”);
      String sample1 =
e.getElementsByTagName(“orig”).item(j).getFirstChild().getNodeValue();
      String sample2 =
e.getElementsByTagName(“trans”).item(j).getFirstChild().getNodeValue();
      result.append(sample1).append(“n”).append(sample2).append(“nn”);
     }
    } 
   }
   

}

  } catch (Exception e) {
   e.printStackTrace();
  }
  return result.toString();
 }
 /**
  * getReslutString
  * @param sb  input String
  * @param patternStr expression
  * @param paramStart substring funtion used start number
  * @param paramEnd substring funtion used end number
  * @param nextRex judge whether need to do ( if it’s chinese string)
  * @return
  * @throws UnsupportedEncodingException
  */
 public static String getReslutString(String sb,String patternStr,int
paramStart,int paramEnd,boolean nextRex) throws
UnsupportedEncodingException{
  StringBuffer result = new StringBuffer();
  Pattern p = Pattern.compile(patternStr);
  Matcher m = p.matcher(sb);
  int n = 0;
  while (m.find()) {
   String eachResult = “”;
   n++;
   int start = m.start() + paramStart;
   int end = m.end() – paramEnd;
   if(nextRex){
    String[] chineseStr = sb.split(“<br>”);
    for(int i=0;i<chineseStr.length-1;i++){
     eachResult = new
String(chineseStr[i].getBytes(“ISO-8859-1″),”GBK”);
     result.append(eachResult + “n”);
    }
   }else{
    eachResult = sb.substring(start, end);
    result.append(eachResult + “n”);
   }
  }
  return result.toString();
 }
 /**
  * getURL
  *
  * @param u
  * @return getURL
  */
 private InputStream getURLInputSteam(String u) {
  URL url;//
  InputStream is;//
  try {
   if (proxyCBox.isSelected() && !””.equals(proxyTxt.getText())) {
    InetSocketAddress address = new InetSocketAddress(proxyURL, 8080);//
设置代理服务器
    Proxy proxy = new Proxy(Proxy.Type.HTTP, address);
    url = new URL(u);
    URLConnection conn = url.openConnection(proxy);
    is = conn.getInputStream();
    return is;
   } else {// 不使用代理
    url = new URL(u);
    is = url.openStream();
    return is;
   }
  } catch (MalformedURLException e) {
   this.setTitle(“必须是有效的URL地址!”);
   return null;
  } catch (IOException e) {
   this.setTitle(“连接出错!”);
   return null;
  }
 } 

实现效果  如下:

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  new SearchWord();
 }
}

澳门新葡萄京官网首页 3

3.

package CLASS16.bin.com.JiSuan;

import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.regex.Pattern;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class MyCalculator extends JFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
public void menu(){
addmenu();

addGridLayout();
addMenu();
//addGridLayout();
}
public void addMenu(){

this.setBackground(getBackground());
setSize(200, 300);//大小
setLocationRelativeTo(null);//居中
setDefaultCloseOperation(EXIT_ON_CLOSE);//关闭
setResizable(false);//不允许修改窗口
setVisible(true);//显示
}
//添加计算器
public void addmenu(){
JMenuBar jmen=new JMenuBar();
super.setJMenuBar(jmen);
// 设置计算器的背景颜色
setBackground(Color.lightGray);
JMenu jmenu=new JMenu(“计算器”);
jmen.add(jmenu);

}
public void addGridLayout(){

/**
* 按钮
*/

//单行文本
JTextArea jtext=new JTextArea(“0.0”);
this.add(jtext, BorderLayout.NORTH);

/**
* 网格布局管理器
*/
GridLayout grid=new GridLayout(4,4,5,5);

// 创建面板对象
JPanel pnl = new JPanel();
grid.addLayoutComponent(getName(), pnl);
pnl.createToolTip();
JButton one1=new JButton(“7”);
JButton one2=new JButton(“8”);
JButton one3=new JButton(“9”);
JButton one4=new JButton(“/”);
JButton two1=new JButton(“4”);
JButton two2=new JButton(“5”);
JButton two3=new JButton(“6”);
JButton two4=new JButton(“*”);
JButton three1=new JButton(“1”);
JButton three2=new JButton(“2”);
JButton three3=new JButton(“3”);
JButton three4=new JButton(“-“);
JButton four1=new JButton(“0”);
JButton four2=new JButton(“.”);
JButton four3=new JButton(“=”);
JButton four4=new JButton(“+”);
one4.setForeground(Color.red);
two4.setForeground(Color.red);
three4.setForeground(Color.red);
four4.setForeground(Color.red);
pnl.add(one1,BorderLayout.NORTH);
pnl.add(one2,BorderLayout.NORTH);
pnl.add(one3,BorderLayout.NORTH);
pnl.add(one4,BorderLayout.NORTH);
pnl.add(two1,BorderLayout.SOUTH);
pnl.add(two2,BorderLayout.SOUTH);
pnl.add(two3,BorderLayout.SOUTH);
pnl.add(two4,BorderLayout.SOUTH);
pnl.add(three1);
pnl.add(three2);
pnl.add(three3);
pnl.add(three4);
pnl.add(four1);
pnl.add(four2);
pnl.add(four3);
pnl.add(four4);
add(pnl);
ActionListener listener=new CListener();

one4.addActionListener(listener);
two4.addActionListener(listener);
three4.addActionListener(listener);
four4.addActionListener(listener);
}
/**
* 监视器
* @param value
*/
public void waynemu(String value){
//正则表达式,输入字符串要求以 零个或一个 – 开头,其余都是数字
Pattern pattern = Pattern.compile(“^-?\d+$”);

if (value == null || value.length() <= 0) {
value = “0”;
}

}
class CListener implements ActionListener{

@Override
public void actionPerformed(ActionEvent e) {
System.out.println(“Is ok!”);

}

}

}

package CLASS16.bin.com.JiSuan;

public class test {

/**
* @param args
*/
public static void main(String[] args) {
MyCalculator my=new MyCalculator();
my.menu();
}

}

实现效果  如下:

澳门新葡萄京官网首页 4<没添加监视器,希望博友可以思考思考>