• java socket demo


    //TCPServer.java
    package msb.demo.socket;
    
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    import java.util.Date;
    
    public class TCPServer {
    
    	/**
    	 * @param args
    	 * @throws IOException
    	 * @throws InterruptedException 
    	 */
    	public static void main(String[] args) throws IOException, InterruptedException {
    
    		ServerSocket serverSocket = new ServerSocket(3333);
    		while (true) {
    			Socket socket = serverSocket.accept();
    			Thread.sleep(2000);
    			//read from client
    			DataInputStream dis = new DataInputStream(socket.getInputStream());
    			String data = dis.readUTF();
    			String msg =(new Date() + " accept:" + data);
    			System.out.println("Server received:"+msg);
    			
    			//write to client
    			DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
    			dos.writeUTF(msg);
    			
    			dis.close();
    			dos.close();
    			socket.close();
    		}
    	}
    
    }
    
    
    //TCPClient.java
    package msb.demo.socket;
    
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.net.Socket;
    import java.net.UnknownHostException;
    
    public class TCPClient {
    
    	static int cnt = 0;
    	/**
    	 * @param args
    	 * @throws IOException 
    	 * @throws UnknownHostException 
    	 */
    	public static void main(String[] args) throws Exception {
    		
    		for(int i=0;i<5;i++)
    			connectServer();
    
    	}
    
    	
    	static void connectServer() throws Exception{
    		Socket socket = new Socket("127.0.0.1",3333);
    		DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
    		//write to server
    		dos.writeUTF("p"+ (++cnt));
    		dos.flush();
    		
    		
    		//read from server
    		DataInputStream dis = new DataInputStream(socket.getInputStream());
    		String msg = dis.readUTF();
    		System.out.println("Client received:"+msg);
    		
    		dos.close();
    		dis.close();
    		socket.close();
    
    	}
    }
    

      

  • 相关阅读:
    ubuntu下进程kidle_inject致使编译软件很慢
    linux下保存下位机输出的串口信息为文件
    ubuntu下转换flv格式为mp4格式
    ubuntu下安装mkfs.jffs工具
    linux下安装evernote国际版
    linux 下使用命令查看jvm信息
    linux下面实时查看进程,内存以及cpu使用情况使用命令
    Java7/8 中的 HashMap 和 ConcurrentHashMap 全解析
    linux如何复制文件夹和移动文件夹
    linux解压war包的命令
  • 原文地址:https://www.cnblogs.com/wucg/p/2664535.html
Copyright © 2020-2023  润新知