Java Socket简单实例

一 服务器端Server.java

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 {
		ServerSocket serverSocket=new ServerSocket(6789);
		while(true){
			Socket socket=serverSocket.accept();
			InputStream inputStream=socket.getInputStream();
			BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
			String string=br.readLine();
			System.out.println("客户端说:"+string);
			br.close();
			inputStream.close();
			socket.close();
		}
	}
}


二 客户端Client.java

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
	public static void main(String[] args) throws UnknownHostException, IOException {
		Socket socket=new Socket("127.0.0.1", 6789);
		OutputStream outputStream=socket.getOutputStream();
		BufferedWriter bWriter=new BufferedWriter(new OutputStreamWriter(outputStream));
		bWriter.write("服务器你好啊!");
		bWriter.close();
		outputStream.close();
		socket.close();
	}
}


三 结果

运行客户端程序三次,结果如下:

客户端说:服务器你好啊!
客户端说:服务器你好啊!
客户端说:服务器你好啊!


你可能感兴趣的:(Java,Socket)