Java套接字基础编程

回顾了一下socket基本编程的内容,记录一下:

Server.java

//package com.liany.demo.socket;

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

public class Server {
	
	private ServerSocket ss;
	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;
	
	public Server(){
		try{
			//监听端口10000
			ss = new ServerSocket(10000);
			System.out.println("Server started, listening to port 10000 ...");
			
			while(true){
				//获取一个套接字
				socket = ss.accept();
				//客户端IP
				String remoteIp = socket.getInetAddress().getHostAddress();
				//端口
				String remotePort = ":" + socket.getLocalPort();
				System.out.println("A client come in! " + remoteIp + remotePort);
				
				//获取套接字内容
				in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				String line = in.readLine();  
				System.out.println("Client sent: " + line);
				
				//向客户端发送内容
				out = new PrintWriter(socket.getOutputStream(), true);
				out.println("Hello, your message received!");
				
				//关闭流和套接字连接
				out.close();
				in.close();
				socket.close();
			}
		}catch (IOException e) {
			System.out.println("Connection failed!");
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new Server();
	}

}

 

Client.java

//package com.liany.demo.socket;

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

public class Client {

	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;
	
	
	public Client(){
		try{
			//对服务器IP和端口发送套接字
			socket = new Socket("127.0.0.1", 10000);
			
			//从控制台输入一行文本
			System.out.println("Please enter some Character:");
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			String line = br.readLine();
			
			//写到套接字
			out = new PrintWriter(socket.getOutputStream(), true);
			out.println(line);
			
			//取得服务器确认文本
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			line = in.readLine();
			System.out.println("Message from server: " + line);

			//关闭流和套接字连接
			br.close();
			out.close();
			in.close();
			socket.close();
		}catch (IOException e) {
			// TODO: handle exception
		}
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new Client();
	}

}
 


Java套接字基础编程_第1张图片

你可能感兴趣的:(socket)