java-基本的Socket编程-实现服务器端和客户端通信

基本的Socket编程:
本实例介绍Socket编程的基本步骤。启动Socket服务后,再打开Socket刻画段,在输入框中输入消息,然后发送给服务器端,服务器端将收到的消息返回到客户端。

关键技术:
Socket编程的关键技术如下;
—–Socket服务器端需要在某个端口上开启服务端类型的Socket,即java.net.ServerSocket。通过他的accept方法等待并接收客户端的请求,返回的是一个java.netSocket对象,如果一直没有客户端请求,那么accept()方法将会一直等待。

—-Socket客户端根据服务器端的IP地址(域名)和端口号创建一个Socket对象,连接服务器端。
—–服务器端和客户端都持有一个Socket对象,服务器端的Socket从服务器端指向客户端,而客户端的Socket从客户端指向服务器端,这就像在客户端和服务器端建立了两条单向的管道。
—通过Socket类提供的getOutputStream方法获得Socket的输出流,getInputStream方法获得Socket输入流。

——————————
本实例分为三个类:SimpleServer实现了Socket服务器端,SimpleClient实现了Socket客户端,ClientFrame类将客户端实现为一个GUI程序。

package com.socket;

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



/*
 * 一个简单的Socket服务器,能接收客户端请求,并将请求返回给客户端
 * 
 */

public class SimpleServer {

    ServerSocket  serverSkt=null;//服务器端侦探听的Socket
    Socket  clientSket=null;//客户端
    BufferedReader  in=null;//客户端输入流
    PrintStream  out=null;//客户端输出流
    //构造方法
    public SimpleServer(int port){
        System.out.println("===服务器正在监听,端口:"+port+"===");
        try{
        serverSkt=new  ServerSocket(port);//创建监听Socket
        }catch(IOException e){
            System.out.println("监听端口+"+port+"失败");
        }

        try{
            clientSket=serverSkt.accept();//接收连接请求
        }catch(IOException  e){
            System.out.println("连接失败");
        }
        //获取输入输出流
        try{
            in=new BufferedReader
                    (new InputStreamReader(clientSket.getInputStream()));
            out=new PrintStream(clientSket.getOutputStream());
        }catch(IOException  e){

        }
    }
    //收到客户端请求
    public  String getRequest(){
            String  frmClt=null;
            try {
                frmClt=in.readLine();
                //从客户端的输入流中读取一行数据
                System.out.print("Server收到请求:"+frmClt);

            } catch (IOException e) {
                // TODO Auto-generated catch block
                System.out.println("无法读取端口.....");
                System.exit(0);
            }
            return  frmClt;
    }

    //发送响应给客户端
    public void sendResponse(String  response){
        try{
            out.println(response);//往客户端输出流中写入数据
            System.out.println("Server响应请求:"+response);
        }catch(Exception e){
            System.out.print("写端口失败");
            System.exit(0);
        }
    }

    public static void main(String[] args) {

        SimpleServer  sa= new SimpleServer(8888);//启动服务器
        while(true){
            //读取客户端的输入并且返回客户端

        }
    }

}
package com.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/*
 * 一个简单的Socket客户端,能够往服务器端发送请求
 */
public class SimpleClient {
    //客户端输入输出流
    PrintStream  out;
    BufferedReader  in;
    //构造方法
    public  SimpleClient(String  serverName,int port){
        //根据服务器端名和端口号,连接服务器
        try {
            Socket  clientSocket=new Socket(serverName, port);
            //获取Socket的输入输出流
            out=new PrintStream(clientSocket.getOutputStream());
            in=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("无法连接到服务器");
        }

    }

    //发送请求
    public void sendRequest(String  request){
        out.println(request);//向Socket的输出流中写数据
        System.out.print("Client发送请求:"+request);

    }


    public String  getReponse(){
        String  str=new  String();
        try{
            str=in.readLine();//从Socket的输入流中读取数据
            System.out.println("Client收到Server返回:"+str);
        }catch(IOException   e){
        }
        return  str;
    }

}
package com.socket;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

/**
 * 客户端的图形界面
 */
public class ClientFrame extends JFrame implements ActionListener {
    // "发送"按钮
    JButton sendButton; 
    // 发送内容的输入框
    JTextField inputField; 
    // 服务器返回内容的文本域
    JTextArea outputArea;

    // 客户端socket对象
    SimpleClient client;

    // 在构造函数中完成图形界面的初始化
    public ClientFrame() {
        JLabel label1 = new JLabel("输入: ");
        inputField = new JTextField(20);
        JPanel panel1 = new JPanel();
        panel1.add(label1);
        panel1.add(inputField);

        JLabel label2 = new JLabel("服务器返回: ");
        outputArea = new JTextArea(6, 20); 
        JScrollPane crollPane = new JScrollPane(outputArea);
        JPanel panel2 = new JPanel();
        panel2.setLayout(new BorderLayout());
        panel2.add(label2, BorderLayout.NORTH);
        panel2.add(crollPane, BorderLayout.CENTER);

        sendButton = new JButton("发 送");
        sendButton.addActionListener(this);

        JPanel panel = new JPanel(); 
        panel.setLayout(new BorderLayout()); 
        panel.add(panel1, BorderLayout.NORTH);
        panel.add(sendButton, BorderLayout.CENTER);
        panel.add(panel2, BorderLayout.PAGE_END);

        setTitle("Socket 客户端");
        this.getContentPane().add(panel);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void actionPerformed(ActionEvent ae) {
        // 判断事件源控件是否是"发送"按钮
        if (ae.getSource() == sendButton) {
            try {
                // 发送文本框中的文本
                client.sendRequest(inputField.getText()); 
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            // 接收服务器回应并写入文本域
            outputArea.append(client.getReponse() + "\n"); 
        }
    }

    public static void main(String[] args) {
        ClientFrame frame = new ClientFrame();
        frame.pack();
        // 连接服务器
        frame.client = new SimpleClient("127.0.0.1", 8888); 
        frame.setVisible(true);

    }

}

  • 4
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值