标签:
import java.io.*; import javax.swing.*; import java.net.*; import java.awt.*; import java.awt.event.*; public class simpleChatClientA { JTextArea incoming; BufferedReader reader; Socket sock; JTextField outgoing; PrintWriter writer; //build the interface public void go(){ JFrame frame = new JFrame("Gaby‘s specific chatClient"); JPanel mainPanel = new JPanel(); /*此处为一大堆GUI组件 incoming 和 JScrollPane的设置 * 我在此忽略 */ outgoing = new JTextField(20); JButton sendButton = new JButton("send"); mainPanel.add(outgoing); mainPanel.add(sendButton); sendButton.addActionListener(new buttonListener()); frame.getContentPane().add(BorderLayout.CENTER, mainPanel); setUpNetWorking(); Thread t = new Thread(new incomingReader()); t.start(); frame.setSize(300, 400); frame.setVisible(true); } //build the link between the class and the server public void setUpNetWorking(){ try{ sock = new Socket("192.168.0.105",5000); InputStreamReader streamReader = new InputStreamReader(sock.getInputStream()); reader = new BufferedReader(streamReader); writer = new PrintWriter(sock.getOutputStream()); System.out.println("networking established"); }catch(Exception ex){ ex.printStackTrace(); } } //register to a button and send message to server class buttonListener implements ActionListener{ public void actionPerformed(ActionEvent ev){ writer.println(outgoing.getText());//因为输出时,只有等到缓冲区满了才输出,有些时候输出的内容比较少的时候,没有充满缓冲区,不会立刻输出的。 writer.flush(); } } //Runnable类使用多线程 public class incomingReader implements Runnable{ String message; public void run(){ try{ while((message = reader.readLine()) != null ){ System.out.println("read " + message); incoming.append(message + "\n"); } }catch(Exception ex){ ex.printStackTrace(); } } } //main public static void main(String args[]){ simpleChatClientA client = new simpleChatClientA(); client.go(); } }
该程序可分为以下功能块:
go:
用于建立GUI,并调用 setUpNetWorking(),并且启动用于接收服务器信息的新线
setUpNetWorking:
通过让Socket sock充当这个对象的实例变量,使得其生存期伴随整个程序
同时,设置好reader和writer
buttonListener implements ActionListener(内部类):
在go里面向button注册了监听,如果遇到click,则由buttonListener对象处理,处理方式则是向服务器发送信息,意味着writer得是实例变量
incomingReader implements Runnable(内部类):
里面的run函数是新线程执行的内容,也因此用到了外部类对象的reader
标签:
原文地址:http://www.cnblogs.com/gabygoole/p/4947746.html