📄 tcpclient.java
字号:
package day16;import java.net.*;import java.util.concurrent.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.*;import javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.JTextField;public class TcpClient { public static void main(String[] args) throws Exception { Socket s = new Socket("localhost", 9000); ClientAWT c = new ClientAWT(s); c.clientRun(); }}class WriteThread implements Callable<Object> { private String text; private Socket s; public WriteThread(String text, Socket s) { super(); this.text = text; this.s = s; } public Object call() { try { OutputStream os = s.getOutputStream(); PrintWriter out = new PrintWriter(os); out.println(text); out.flush(); } catch (IOException e) { e.printStackTrace(); } return null; }}class ReadThread implements Callable<Object> { private Socket s; JTextArea jta; public ReadThread(Socket s, JTextArea jta) { this.s = s; this.jta = jta; } public Object call() { try { InputStream is = s.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String str; while ((str = in.readLine()) != null) { jta.append(str + "\n"); } } catch (IOException e) { e.printStackTrace(); } return null; }}class ClientAWT { private Socket s; public ClientAWT(Socket s) { super(); this.s = s; } public void clientRun() { JFrame frame = new JFrame("Chat Client"); frame.setSize(400, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final JTextArea jta = new JTextArea(); final JTextField jtf = new JTextField(); frame.add(new JScrollPane(jta)); frame.add(jtf, "South"); jta.setEditable(false); frame.setVisible(true); final ExecutorService es = Executors.newFixedThreadPool(2); jtf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String text = jtf.getText(); Callable<Object> c1 = new WriteThread(text, s); es.submit(c1); jtf.setText(""); } }); Callable c2 = new ReadThread(s, jta); es.submit(c2); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -