标签:客户机 npe nec serve 127.0.0.1 method win ring nta
服务器端
package text; import java.io.*; import java.net.*; public class MyTcp { private BufferedReader reader; private ServerSocket server; private Socket socket; void getserver(){ try { server = new ServerSocket(8998); System.out.println("服务器套接字已经创建成功"); while (true) { System.out.println("等待客户机的链接"); socket = server.accept(); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); getClientMessage(); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } private void getClientMessage() { // TODO Auto-generated method stub try { while ( true) { System.out.println("客户机"+ reader.readLine()); } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } try { if(reader == null){ reader.close(); } if(socket!= null){ socket.close(); } } catch (IOException e) { // TODO: handle exception e.printStackTrace(); } } public static void main(String[] args) { // TODO Auto-generated method stub MyTcp tcp = new MyTcp(); tcp.getserver(); } }
客户端
package text; import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.PrintWriter; import java.net.Socket; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.border.BevelBorder; public class MyClien extends JFrame{ private PrintWriter writer ; Socket socket ; private JTextArea ta = new JTextArea(); private JTextField tf = new JTextField(); Container cc; public MyClien(String title) { // TODO Auto-generated constructor stub super(title); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); cc = this.getContentPane(); final JScrollPane scrollPane = new JScrollPane(); scrollPane.setBorder(new BevelBorder(BevelBorder.RAISED)); getContentPane().add(scrollPane, BorderLayout.CENTER); scrollPane.setViewportView(ta); cc.add(tf, "South"); tf.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub writer.println(tf.getText()); ta.append(tf.getText() + ‘\n‘); ta.setSelectionEnd(ta.getText().length()); tf.setText(""); } }); } private void connect() { ta.append("尝试连接\n"); try { socket = new Socket("127.0.0.1", 8998); writer = new PrintWriter(socket.getOutputStream(),true); ta.append("完成链接\n"); } catch (Exception e) { // TODO: handle exceptio e.printStackTrace(); } } public static void main(String[] args) { // TODO Auto-generated method stub MyClien clien = new MyClien("向服务器发送数据"); clien.setSize(200,200); clien.setVisible(true); clien.connect(); } }
标签:客户机 npe nec serve 127.0.0.1 method win ring nta
原文地址:https://www.cnblogs.com/dulute/p/10654139.html