传统的Socket编程

254 阅读2分钟

基于TCP的socket实现

public class SocketClient {
	
	public static void main(String[] args) throws InterruptedException {
		try {
			// 和服务器创建连接
			Socket socket = new Socket("localhost",8088);
			
			// 要发送给服务器的信息
			OutputStream os = socket.getOutputStream();
			PrintWriter pw = new PrintWriter(os);
			pw.write("客户端发送信息");
			pw.flush();
			
			socket.shutdownOutput();
			
			// 从服务器接收的信息
			InputStream is = socket.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String info = null;
			while((info = br.readLine())!=null){
				System.out.println("我是客户端,服务器返回信息:"+info);
			}
			
			br.close();
			is.close();
			os.close();
			pw.close();
			socket.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 
}
public class SocketServer {
	
	public static void main(String[] args) {
		try {
			// 创建服务端socket
			ServerSocket serverSocket = new ServerSocket(8088);
			
			// 创建客户端socket
			Socket socket = new Socket();	
			
			//循环监听等待客户端的连接
            while(true){
            	// 监听客户端
            	socket = serverSocket.accept();
            	
            	ServerThread thread = new ServerThread(socket);
            	thread.start();
            	
            	InetAddress address=socket.getInetAddress();
                System.out.println("当前客户端的IP:"+address.getHostAddress());
            }
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
 
}
public class ServerThread extends Thread{
	
	private Socket socket = null;
	
	public ServerThread(Socket socket) {
		this.socket = socket;
	}
 
	@Override
	public void run() {
		InputStream is=null;
        InputStreamReader isr=null;
        BufferedReader br=null;
        OutputStream os=null;
        PrintWriter pw=null;
        try {
			is = socket.getInputStream();
			isr = new InputStreamReader(is);
			br = new BufferedReader(isr);
			
			String info = null;
			
			while((info=br.readLine())!=null){
				System.out.println("我是服务器,客户端说:"+info);
			}
			socket.shutdownInput();
			
			os = socket.getOutputStream();
			pw = new PrintWriter(os);
			pw.write("服务器欢迎你");
			
			pw.flush();
        } catch (Exception e) {
			// TODO: handle exception
		} finally{
			//关闭资源
            try {
                if(pw!=null)
                    pw.close();
                if(os!=null)
                    os.close();
                if(br!=null)
                    br.close();
                if(isr!=null)
                    isr.close();
                if(is!=null)
                    is.close();
                if(socket!=null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
		}
	}
}

基于UDP的socket实现

public class SocketClient {
	
	public static void main(String[] args) {
		try {
            // 要发送的消息
            String sendMsg = "客户端发送的消息";
            
            // 获取服务器的地址
            InetAddress addr = InetAddress.getByName("localhost");
            
            // 创建packet包对象,封装要发送的包数据和服务器地址和端口号
            DatagramPacket packet = new DatagramPacket(sendMsg.getBytes(),
            		sendMsg.getBytes().length, addr, 8088); 
            
            // 创建Socket对象
            DatagramSocket socket = new DatagramSocket();
            
            // 发送消息到服务器
            socket.send(packet);
 
            // 关闭socket
            socket.close();
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
	}
}
public class SocketServer {
	
	public static void main(String[] args) {
		try {
			 // 要接收的报文
			byte[] bytes = new byte[1024];
			DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
			
			// 创建socket并指定端口
			DatagramSocket socket = new DatagramSocket(8088);
			
			// 接收socket客户端发送的数据。如果未收到会一致阻塞
			socket.receive(packet);
			String receiveMsg = new String(packet.getData(),0,packet.getLength());
			System.out.println(packet.getLength());
			System.out.println(receiveMsg);
			
			// 关闭socket
			socket.close();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
 
}

参考

socket编程