java socket实现简单的客户端请求和响应

来源: 易习特达网 www.easytd.com 时间: 2016-01-05 07:35:30

java socket实现简单的客户端请求和响应

socket服务器端代码:

package com.wang;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

public class ServerSocket1

{

    private ServerSocket socketServer;

    private Socket socket;

    private BufferedReader in;

    private PrintWriter out;

    public ServerSocket1()

    {

        try

        {

            // 定义socket通信

            socketServer = new ServerSocket(10000);

            // 接收来自客户端的socket

            socket = socketServer.accept();

            // 获得来自于客户端的字节输入流

            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // 获得来自于客户端的输出流

            out = new PrintWriter(socket.getOutputStream(), true);

            String line = in.readLine();

            System.out.println("您输出的是:" + line);

            out.println("you input is :" + line);

            out.close();

            in.close();

            socket.close();

        }

        catch (IOException e)

        {

        }

    }

    public static void main(String args[])

    {

        new ServerSocket1();

    }

}

Socket客户端代码:

package com.wang;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.InetAddress;

import java.net.Socket;

public class Socket1

{

    Socket socket;

    BufferedReader in;

    PrintWriter out;

    public Socket1()

    {

        try

        {

            socket = new Socket(InetAddress.getLocalHost(), 10000);

            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            out = new PrintWriter(socket.getOutputStream(), true);

            BufferedReader line = new BufferedReader(new InputStreamReader(System.in));

            out.println(line.readLine());

            System.out.println("接收来自于server的:"+in.readLine());

            line.close();

            out.close();

            in.close();

            socket.close();

        }

        catch (IOException e)

        {

            e.printStackTrace();

        }

    }

    public static void main(String args[])

    {

        new Socket1();

    }

}

本页地址:http://www.easytd.com/chengxudaima/d_16010507892.html

常用工具