Socket编程入门(一)实现简单的Socket实例

使用Socket编写了一个服务端和客户端通讯的例子,下面帖代码,本文使用了java7的部分特性,因此需要jdk至少7以上。

客户端:


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public final class Client {
	final static int PORT = 8088;
	final static String ADDRESS = "127.0.0.1";

	public static void main(String[] args) {
		
		try (Socket socket = new Socket(ADDRESS, PORT);
				BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				PrintWriter out = new PrintWriter(socket.getOutputStream(), true);) {
			while(true) {//循环发送消息
			// 向服务器端发送数据
			out.println("今天天气怎么样?");
			String response = in.readLine();
			System.out.println("from server:"+response);
			out.println("我想知道我在服务器的积分是多少?");
			Thread.sleep(2000);
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

服务器端:

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	final static int PORT = 8088;

	public static void main(String[] args) {
		ServerSocket server = null;
		try {
			server = new ServerSocket(PORT);
			System.out.println("Server is start....");
			while (true) {//通过循环使服务器可持续接收请求
				// 进行阻塞,这里阻塞的是循环,但是当有请求传入时会放行一次
				Socket socket = server.accept();
				new Thread(new ServerHandler(socket)).start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

ServerHandler类


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class ServerHandler implements Runnable {
	private Socket socket;

	public ServerHandler(Socket socket) {
		this.socket = socket;
	}

	@Override
	public void run() {
		try(BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				PrintStream out = new PrintStream(socket.getOutputStream(), true);){
			String body = null;
			while (true) {
				body = in.readLine();
				if (body == null)
					break;
				System.out.println("from Client:" + body);
				out.println("我是服务器返回的数据");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

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