Simple tcp communication code for network programming

 

 

1 Look at the client server code under a simple tcp communication:

 

/**
 1. To create a client, you must specify the server + port to connect at this time
 	Socket(String host, int port)
 2. Receive data + send data	
 * @author Administrator
 *
 */
public class Client {

	/**
	 * @param args
	 * @throws IOException
	 * @throws UnknownHostException
	 */
	public static void main(String[] args) throws UnknownHostException, IOException {
		//1. To create a client, you must specify the server + port to connect at this time
		Socket client = new Socket("localhost",8888);
		//2, receive data
		/*
		BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
		String echo =br.readLine(); //Blocking method
		System.out.println(echo);
		*/
		DataInputStream dis = new DataInputStream(client.getInputStream());
		String echo = dis.readUTF();
		System.out.println(echo);
	}

}

Server:

/**
 You must start the server before connecting
1. Create the server specified port ServerSocket(int port)
2. Receive client connections  
3. Send data + receive data
*
*/
public class Server {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		//1. Create the server specified port ServerSocket(int port)
		ServerSocket server = new ServerSocket(8888);
		//2, receive client connection blocking
		Socket socket =server.accept();
		System.out.println("A client establishes a connection");
		//3, send data
		String msg = "Welcome";
		//output stream
		/*
		BufferedWriter bw = new BufferedWriter(
				new OutputStreamWriter(
				socket.getOutputStream()));
		
		bw.write(msg);
		bw.newLine();
		bw.flush();
		
		
		*/
		DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
		dos.writeUTF(msg); // The server writes out data
		dos.flush();
		
	}

}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326531005&siteId=291194637