美文网首页
Java TCP网络通信

Java TCP网络通信

作者: 一杯清凉的水 | 来源:发表于2018-04-10 23:37 被阅读0次

    试上高峰窥浩月,偶开天眼觑红尘,可怜身是眼中人


    Java TCP网络通信

    InetAddress类

    package page1;
    
    import java.net.InetAddress;
    import java.net.UnknownHostException;
    
    public class MyTcp {
        public static void main(String[] args) {
            InetAddress ip;
            try {
                ip=InetAddress.getLocalHost();
                System.out.println("主机名:" + ip.getHostName());
                System.out.println("IP:" + ip.getHostAddress());
                
            } catch (UnknownHostException e) {
                
                e.printStackTrace();
            }
            
        }
    }
    
    
    image.png

    TCP网络程序

    服务器端

    package page2;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class TCP_Server {
    
        private BufferedReader reader;//从字符输入流中读取文本
        private ServerSocket server;//服务器套接字
        private Socket socket;//客户端套接字
        
        void getServer() throws Exception {
        
            server=new ServerSocket(1865);//创建套接字绑定到1865端口
            System.out.println("服务器套接字创建成功");
            while(true)
            {
                System.out.println("等待计算机的连接");
                socket=server.accept();//等待客户端连接,若连接,创建一个套接字
                reader=new BufferedReader(new InputStreamReader(socket
                        .getInputStream()));
                getClientMassage();
            }   
        }
        
        private void getClientMassage() throws Exception {
            
            while(true) 
            {
                System.out.println("Tsthzang:" + reader.readLine());
            }       
        }
        
        public static void main(String[] args) throws Exception {
            
            TCP_Server tcp_server=new TCP_Server();
            tcp_server.getServer();
        }       
    }
    
    

    客户端

    package page2;
    
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    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 TCP_Client extends JFrame{
        
        private PrintWriter writer;
        Socket socket;
        private JTextArea ta=new JTextArea();
        private JTextField tf=new JTextField();
        Container cc;
        
        public TCP_Client(String title) {
            
            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 arg0) {
                    
                    writer.println(tf.getText());
                    ta.append(tf.getText()+'\n');
                    ta.setSelectionEnd(ta.getText().length());
                    tf.setText("");     
                }
            }); 
        }
        
        private void connect() throws Exception {
            
            ta.append("尝试连接\n");
            
            socket=new Socket("127.0.0.1", 1865);
            writer=new PrintWriter(socket.getOutputStream(),true);
            ta.append("连接完成\n");
        }
        
        public static void main(String[] args) throws Exception {
            
            TCP_Client client=new TCP_Client("聊天程序客户端");
            client.setSize(200,200);
            client.setVisible(true);
            client.connect();
        }
        
    }
    
    
    image.png

    PS . 完整服务器端程序:

    package page2;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.ServerSocket;
    import java.net.Socket;
    
    public class TCP_Server {
    
        private BufferedReader reader;//从字符输入流中读取文本
        private ServerSocket server;//服务器套接字
        private Socket socket;//客户端套接字
        
        void getServer() {
            
            try {
                server=new ServerSocket(1865);
                System.out.println("服务器套接字创建成功");
                while(true)
                {
                    System.out.println("等待计算机的连接");
                    socket=server.accept();
                    reader=new BufferedReader(new InputStreamReader(socket
                            .getInputStream()));
                    getClientMassage();
                }
            } 
                catch (IOException e)
                {
                    e.printStackTrace();
                }
        }
        
        private void getClientMassage() {
            
            try{
                while(true) 
                {
                    System.out.println("Tsthzang:" + reader.readLine());
                }       
            } 
                catch (IOException e) {
                    e.printStackTrace();
                }
            
            try {
                if(reader!=null) {
                    reader.close();
                }
                if(socket!=null) {
                    socket.close();
                }
            }
                catch (IOException e) {
                    e.printStackTrace();
                }
        }
        
        public static void main(String[] args) {
            
            TCP_Server tcp_server=new TCP_Server();
            tcp_server.getServer();
        }
                
    }
    

    总结:

    ServerSocket类

    ServerSocket的构造方法都抛出IOException

    accept();//等待客户端连接,若连接,创建一个套接字(返回值:Socket)
    bind(SocketAddress endpoint);//绑定到特定地址(IP地址和端口号)
    
    isBound();//判断ServerSocket的绑定状态
    
    getInetAddress();//返回此服务器套接字的本地地址(返回值:InetAddress)
    getInetAddress();//返回此服务器套接字等待的端口号(返回值:int)
    
    isClosed();//判断关闭状态
    close();//关闭
    

    参考资料:

    相关文章

      网友评论

          本文标题:Java TCP网络通信

          本文链接:https://www.haomeiwen.com/subject/iayohftx.html