Java socket 实现tcp通信

客户端:Client

package socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
	private static final String SERVER_IP = "localhost";
	private static final int PORT = 9999;

	public static void main(String [] args) throws UnknownHostException, IOException{
		Socket socket = new Socket(SERVER_IP, PORT);
//		BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getOutputStream()));
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
		writer.write("message");
		writer.flush();
		socket.close();
	}
}

服务器端:Server

package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	private static final int PORT = 9999;
	public static void main(String [] args) throws IOException{
		ServerSocket server = new ServerSocket(PORT);
		Socket socket = server.accept();
		BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		System.out.println("server : "+reader.readLine());
		socket.close();
	}

}





你可能感兴趣的:(Java socket 实现tcp通信)