socket 实现简单通信

注:书上的代码,简单记录。先启动serverSocket。

主要思想:C/S模式,一个客户socket,一个serverSocket。

        客户socket负责建立连接,发送请求到serverSocket,并读取数据。

        serverSocket继承Thread类,源源不断的提供服务,并记录请求的数量。

知识点:socket类,io流,线程。

具体代码

public class SocketDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			Socket socket = new Socket("127.0.0.1",8090);
			PrintStream printStream = new PrintStream(socket.getOutputStream());
			printStream.println("我是lemon");
			printStream.flush();
			
			
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String line = bufferedReader.readLine();
			
			System.out.println("来自服务器的信息: "+line);
			
			bufferedReader.close();
			printStream.close();
			socket.close();
			
			
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

	}

}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
 * 
 * @describe 创建serverSocket 多线程
 * 			继承Thread
 *
 */

public class ServerSocketDemo extends Thread{
	
	ServerSocket serverSocket;
	int i = 0;
	
	public ServerSocketDemo() {
		try {
			serverSocket = new ServerSocket(8090);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		this.start();
		System.out.println("服务器启动……");
	}
	
	public void run() {
		while(this.isAlive()) {
			try {
				Socket socket =  serverSocket.accept();
				BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				
				String line = br.readLine();
				System.out.println(line);
				
				PrintStream ps = new PrintStream(socket.getOutputStream());
				ps.println("您是第"+ (i++)+"个访问服务器的用户");
				ps.flush();
				br.close();
				socket.close();
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	
	public static void main(String[] args) {
		new ServerSocketDemo();

	}

}

运行截图

socket 实现简单通信_第1张图片

socket 实现简单通信_第2张图片

 

 

你可能感兴趣的:(java)