首页 > 代码库 > Java学习笔记_网络(2)
Java学习笔记_网络(2)
单向的客户端发送服务器端接收并显示,没有使用多线程
1 import javax.swing.*; 2 import java.awt.*; 3 import java.io.*; 4 import java.net.*; 5 import java.awt.event.*; 6 7 public class ChatClient { 8 private JTextArea text_area; 9 private PrintWriter writer; 10 private Socket s; 11 12 public static void main(String[] args) { 13 ChatClient client = new ChatClient(); 14 client.go(); 15 } 16 17 private void go() { 18 build_gui(); 19 setup_net(); 20 } 21 22 private void build_gui() { 23 JFrame frame = new JFrame("Chat Client"); 24 JPanel panel = new JPanel(); 25 text_area = new JTextArea(1, 20); 26 panel.add(text_area); 27 JButton button = new JButton("Send"); 28 button.addActionListener(new SendButtonListener()); 29 panel.add(button); 30 frame.add(BorderLayout.CENTER, panel); 31 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 32 frame.setBounds(50, 50, 400, 100); 33 frame.setVisible(true); 34 } 35 36 public class SendButtonListener implements ActionListener { 37 public void actionPerformed(ActionEvent a) { 38 String msg = text_area.getText(); 39 System.out.println(msg); 40 writer.println(msg); 41 writer.flush(); //如果没有则服务器端收不到消息 42 } 43 } 44 45 private void setup_net() { 46 try { 47 s = new Socket("127.0.0.1", 4242); 48 writer = new PrintWriter(s.getOutputStream()); 49 } catch (IOException ex) { 50 ex.printStackTrace(); 51 } 52 } 53 }
1 import java.io.*; 2 import java.net.*; 3 4 public class ChatServer { 5 6 public static void main(String[] args) { 7 ChatServer server = new ChatServer(); 8 server.go(); 9 } 10 11 private void go() { 12 setup_net(); 13 } 14 15 private void setup_net() { 16 try { 17 ServerSocket serverSock = new ServerSocket(4242); 18 while (true) { 19 Socket s = serverSock.accept(); 20 System.out.println("client connected"); 21 InputStreamReader streamReader = new InputStreamReader( s.getInputStream() ); 22 BufferedReader reader = new BufferedReader( streamReader ); 23 String msg; 24 try { //如果没有这个try则当客户端关闭后会异常退出 25 while ( (msg = reader.readLine()) != null ) { 26 System.out.println(msg); 27 } 28 } catch (IOException ex) { System.out.println("client disconnected"); } 29 } 30 } catch (IOException ex) { 31 ex.printStackTrace(); 32 } 33 } 34 }
Java学习笔记_网络(2)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。