socket通信原理以及实现

服务端

package com.hmsm.socket.server;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 模拟查询天气
 * Socket 服务端
 * @author Administrator
 *
 */
public class SocketServer {
	public static void main(String[] args) throws IOException {
		
        //启动socket服务端
		ServerSocket serverSocket=new ServerSocket(55555);
		System.out.println("服务端已启动。。。");
		DataInputStream inputStream=null;
		DataOutputStream outputStream=null;
		while(true){
			try {
			//监听客户端连接 accept()是阻塞方法
			Socket socket=  serverSocket.accept();
			
			//先接收从客户端发送过来的数据
			inputStream=new DataInputStream(socket.getInputStream()) ;
			 //城市名称
			 String cityName=inputStream.readUTF();
			 //接收客户端传送过来的城市名称
			 System.out.println("from client。。。"+cityName);
			
			
			//再通过服务端发送出去
			outputStream=new DataOutputStream(socket.getOutputStream());
		        String result="晴转阴";
			 //将查询结果发送出去
			 outputStream.writeUTF(result);
			 System.out.println("to client。。。"+result);
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				if(inputStream!=null){
					inputStream.close();
				}
				if(outputStream!=null){
					outputStream.close();
				}
			}
		}
		
	}
}

客户端

package com.hmsm.socket.client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

/**
* 模拟查询天气
* Socket 客户端
* @author Administrator
*
*/
public class SocketClient {
    public static void main(String[] args) throws UnknownHostException, IOException {
    	//创建Socket连接
    	Socket socket=new Socket("127.0.0.1",55555);
    	
    	
    	DataInputStream inputStream=null;
    	DataOutputStream outputStream=null;
    	try {
    		//发送数据
    		 outputStream=new DataOutputStream(socket.getOutputStream());
    		String cityName="成都";
    		outputStream.writeUTF(cityName);
    		System.out.println("to server。。。"+cityName);
    		
    		
    		//接收数据
    		 inputStream=new DataInputStream(socket.getInputStream());
    		String result=inputStream.readUTF();
    		System.out.println("from server。。。"+result);
    		
    	} catch (Exception e) {
    		e.printStackTrace();
    	}finally{
    		if(outputStream!=null){
    			outputStream.close();
    		}
    		if(inputStream!=null){
    			inputStream.close();
    		}
    		if(socket!=null){
    			socket.close();
    		}
    	}
    }
}

你可能感兴趣的:(Webservice)