获取数据的方式

来源:互联网 发布:头号共谍常凯申 知乎 编辑:程序博客网 时间:2024/05/17 21:41

目前获取数据的方式有:

Socket、Http、WebService.

一个简单的socket案例:

import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;import java.util.Scanner;public class SocketClient {/** * @param args * @throws IOException * @throws UnknownHostException * @throws InterruptedException */public static void main(String[] args) throws UnknownHostException,IOException, InterruptedException {// TODO Auto-generated method stubScanner input = new Scanner(System.in);System.out.println("please input...");String dataString = input.next();Socket sc = new Socket("127.0.0.1", 9999);OutputStream out = sc.getOutputStream();out.write(dataString.getBytes());System.out.println("wait response...");InputStream inputStream = sc.getInputStream();byte[] b = new byte[1024];int length = inputStream.read(b);System.out.println("response:" + new String(b, 0, length));input.close();out.close();sc.close();}}

import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;public class SocketServer {/** * @param args * @throws IOException */public static void main(String[] args) throws IOException {// TODO Auto-generated method stubServerSocket serverSocket = new ServerSocket(9999);System.out.println("wait requests from clients.");Socket socket = serverSocket.accept();System.out.println("receive the request from client.");InputStream input = socket.getInputStream();byte[] b = new byte[1024];int len = input.read(b);String data = new String(b, 0, len);System.out.println("receive data:" + data);OutputStream outputStream = socket.getOutputStream();outputStream.write(data.toUpperCase().getBytes());input.close();outputStream.close();socket.close();}}
示意图如下:



0 0