码迷,mamicode.com
首页 > 编程语言 > 详细

[Java]网络编程

时间:2014-12-20 18:14:10      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

同学的程序:
package day13.me.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/** socket 编程 - 服务器端 */
public class MyTcpServer {
    private BufferedReader reader;
    private PrintWriter writer;
    private ServerSocket server;
    private Socket socket;

    void getServer() {
        try {
            server = new ServerSocket(8998);
            System.out.println("服务器套接字已经创建成功");
            while (true) {
                System.out.println("等待客户机连接");
                socket = server.accept();
                System.out.println("客户机连接成功");
                reader = new BufferedReader(new InputStreamReader(socket
                        .getInputStream()));
                writer = new PrintWriter(socket.getOutputStream(), true);
                getClientMessage();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getClientMessage() {
        try {
            while (true) {
                if (reader.ready()) {
                    String s = reader.readLine();
                    System.out.println("客户机:" + s);
                    writer.println("Server Received:" + s);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (reader != null)
                reader.close();
            if (writer != null)
                writer.close();
            if (socket != null)
                socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        MyTcpServer tcpServer = new MyTcpServer();
        tcpServer.getServer(); // 调用方法
    }
}

package day13.me.net;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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;

/** socket 编程 - 客户端 */
public class MyClient extends JFrame{
    
    private PrintWriter writer;
    private BufferedReader reader;
    Socket socket;
    private JTextArea ta = new JTextArea();
    private JTextField tf = new JTextField();
    Container cc;
    
    public MyClient(String title){
        super(title);
        this.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(){
            public void actionPerformed(ActionEvent e){
                try{
                    writer.println(tf.getText());// 将文本框中信息写入流
                    ta.append(tf.getText()+‘\n‘    ); // 将文本框中信息显示在文本域中
                    ta.append(reader.readLine()+‘\n‘);
                    ta.setSelectionEnd(ta.getText().length());
                    tf.setText(""); // 将文本框清空        
                } catch(IOException ee){
                    ee.printStackTrace();
                }
            }
        });
    }

    private void connect() throws IOException{
        ta.append("尝试连接\n");
        String hostIP = "10.10.74.7";
        try{
            socket = new Socket("localhost",8998);
            writer = new PrintWriter(socket.getOutputStream(),true);
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            ta.append("完成连接\n");
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException{
        MyClient client = new MyClient("向服务器送数据");
        client.setSize(200,200);
        client.setLocation(700,300);
        client.setVisible(true);
        client.connect();
    }


}

 

老师的程序:
package net;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;


public class Client {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        try {
            
            Socket socket = new Socket("10.10.74.2",8888);
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            
            String line;

            while( !(line = in.readLine()).equals("bye")){
                
                
                bw.write(line);
                bw.flush();
                System.out.println("服务端:" + br.readLine());
                
            }
            
            socket.close();
            
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

}
package net;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * ServerSocket,顾名思义,是用来监听端口并接受用户连接的。
 * 我们创建一个 ServerSocket,在构造函数里把想要监听的端口传给它,它就绑定了我们所指定的端口。
 * 当我们调用 accept 方法的时候,程序就进入了阻塞状态,也就是说停在 accept 这句不再往下运行了,等待用户连接。
 * 当一个用户连接到指定的端口时,accept 方法返回一个 Socket,这个 Socket 就是我们用来与用户进行交互的通道。
 * 通过 Socket 我们可以获取一个 OutputStream 用来向客户端发送数据,也可以获取一个 InputStream 从客户端读取数据。
 */

public class ServerSocketDemo {
    
    public static void main(String[] args){
        
        try {
            
            ServerSocket server = new ServerSocket(8888);
            
            Socket socket = server.accept();
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
            
            String line;
            while(true){
                                
                line = br.readLine();
                System.out.println(socket.getInetAddress().getHostAddress()+"->"+line);
                String line1 = br1.readLine();
                bw.write(line1);
                bw.flush();
                
            }
            
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
    }

}

 

[Java]网络编程

标签:

原文地址:http://www.cnblogs.com/lkboy/p/4175630.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!