socket 客户端 java_java 客户端socket

gistfile1.txt

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.IOException;

import java.net.Socket;

import java.net.UnknownHostException;

import java.util.Scanner;

/**

* 客户端Socket

* @author YJ

*/

public class Client{

private DataInputStream isFromServer;//数据输入流

private DataOutputStream osToServer;//数据输出来

private Socket connectToServer;//连接服务端socket

private Scanner input;//接收控制台输入数据

public Client(){

try {

connectToServer = new Socket("localhost", 8000);//创建连接服务器的socket

isFromServer = new DataInputStream(connectToServer.getInputStream());

osToServer = new DataOutputStream(connectToServer.getOutputStream());

while(true){//可多次输入

System.out.print("Please enter a int: ");

input = new Scanner(System.in);//接收控制台输入数据

osToServer.writeInt(input.nextInt());//将数据传给服务端

osToServer.flush();//清空输出流

int i = isFromServer.readInt();//读入服务端传来的数据

System.out.println("the returned value is: "+i);

}

} catch (UnknownHostException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

public static void main(String[] args){

new Client();

}

}