package com.liubo.webservice.socket.Client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
/*
* 用Socket方法实现Webservice
* Socket客户端
*/
public class SocketClient {
public static void main(String[] args) throws UnknownHostException, IOException{
Socket socket=null;
DataInputStream getInputStream=null;
DataOutputStream getOutStream=null;
try {
// 客户端创建一个socket
socket = new Socket("127.0.0.1", 12345);
System.out.println("客户端服务已连接....");
// 发送数据,创建一个输出流来向服务端发送数据
getOutStream = new DataOutputStream(socket.getOutputStream());
// 发送城市
String cityname = "北京121";
getOutStream.writeUTF(cityname);
System.out.println("向服务端发送信息..." +cityname);
// 接收数据,创建一个输入流来接收数据
getInputStream = new DataInputStream(socket.getInputStream());
String result = getInputStream.readUTF();
System.out.println("从服务端接受的信息..." +result);
} catch (Exception e) {
e.printStackTrace();
}finally{
//释放资源
if(socket!=null){
socket.close();
}
if(getInputStream!=null){
getInputStream.close();
}
if(getOutStream!=null){
getOutStream.close();
}
}
}
} |
|