简单的Socket通信

 

public class Client {

	public static void main(String[] args) throws UnknownHostException,
			IOException {
		System.out.println("-- client start. -- ");
		String s = "";

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		s = br.readLine();
		while (!s.equals("bye")) {
			Socket socket = new Socket("localhost", 8804);
			DataOutputStream out = new DataOutputStream(socket.getOutputStream());
			DataInputStream in = new DataInputStream(socket.getInputStream());
			
			out.writeUTF(s);
			System.out.println("Server: " + in.readUTF());
			s = br.readLine();
		}
		System.out.println("-- client stop! --");

	}

}

public class Server {
	static int counter = 0;

	public static void main(String[] args) throws IOException {

		System.out.println("-- server start. --");

		ServerSocket server = new ServerSocket(8804);
		String a = "";

		do {
			Socket socket = server.accept();

			DataInputStream in = new DataInputStream(socket.getInputStream());
			DataOutputStream out = new DataOutputStream(
					socket.getOutputStream());

			a = in.readUTF();
			System.out.println("Client: " + a);

			out.writeUTF(a + " - " + counter++);
		} while (!a.equals("bye"));

		System.out.println("-- server stop. --");
	}

}

  

 

http://blog.csdn.net/liu149339750/article/details/7868799

posted @ 2016-07-12 18:01  搜索技术  阅读(199)  评论(0编辑  收藏  举报