Java学习笔记_网络
Posted Ren.Yu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java学习笔记_网络相关的知识,希望对你有一定的参考价值。
单向的客户端发送服务器端接收并显示,没有使用多线程
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学习笔记_网络的主要内容,如果未能解决你的问题,请参考以下文章
[原创]java WEB学习笔记61:Struts2学习之路--通用标签 property,uri,param,set,push,if-else,itertor,sort,date,a标签等(代码片段