使用Java网络编程创建基于TCP协议的Server和Client

package com.ch10_network;

import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class TCPServerA {
	public static void main(String[] args) throws Exception {
		ServerSocket serverSocket = new ServerSocket(8888);
		Socket socket = serverSocket.accept();
		OutputStream os = socket.getOutputStream();
		PrintWriter pw = new PrintWriter(os);
		pw.write("now time = "+new Date());
		pw.flush();
		pw.close();
		serverSocket.close();
		socket.close();
	}
}

package com.ch10_network;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class TCPClientA {
	public static void main(String[] args) throws Exception{
		Socket socket = new Socket("localhost",8888);
		InputStream is = socket.getInputStream();
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(isr);
		String string = br.readLine();
		System.out.println(string);
		is.close();
		br.close();
		socket.close();
		isr.close();
	}
}

你可能感兴趣的:(Java)