Java学习 TCP通信

服务端: 

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

public class Server {

	public static void main(String[] args) throws IOException {
		System.out.println("服务器启动...");
		//创建服务器端ServerSocket 端口号为 6789
		ServerSocket serverSocket = new ServerSocket(6789);
		//建立Socket来接收客户端的Socket对象 accept()是阻塞式的
		Socket socket = serverSocket.accept();
		//获取Socket的输入流
		InputStream is = socket.getInputStream();
		//将字节流转换成字符流
		InputStreamReader isr = new InputStreamReader(is);
		//建立缓冲区 方便操作
		BufferedReader br = new BufferedReader(isr);
		String line = null;
		while((line = br.readLine())!=null){
			System.out.println(line);
		}
		
		//关闭资源
		serverSocket.close();
		socket.shutdownInput();
		is.close();
		isr.close();
		br.close();
		
	}

}

客户端:

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {

	public static void main(String[] args) throws IOException{
		//建立客户端的Socket对象 端口必须和服务器端的一致
		Socket socket = new Socket("127.0.0.1",6789);
		//输出流用于向Socket输出数据
		OutputStream os = socket.getOutputStream();
		//打印流修饰一下 方便write()
		PrintWriter pw = new PrintWriter(os);
		String ip = socket.getInetAddress().getHostAddress();
		pw.write(ip+"给我发的消息:");
		pw.write("封神伯纳乌");
		//将输出流的字符缓冲流 刷新一下
		pw.flush();
		
		//关闭资源
		socket.close();;
		os.close();
		pw.close();
}

}

结果:

服务器启动...
127.0.0.1给我发的消息:封神伯纳乌

你可能感兴趣的:(java)