Java - 实现 Socket 程序

 

写一个 MyServerSocket 程序, 用来接收 8081 端口的请求信息.

 

package com.javalearn.socket;

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

public class MyServerSocket {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ServerSocket serverSocket = null;
		Socket clientSocket = null;
		BufferedReader br = null;
		try {
			// 服务器套接字, 使用 8081 端口
			serverSocket = new ServerSocket(8081);
			// 由服务器套接字生成 套接字 对象, 开始监听网络, 等待接收客户端消息
			clientSocket = serverSocket.accept();
			// 接收 客户端套接字 消息
			br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			// 消息打印
			String temp = null;
			while((temp = br.readLine()) != null) {
				System.out.println(temp);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// 资源关闭
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (clientSocket != null) {
				try {
					clientSocket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (serverSocket != null) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

}

 

写一个 MyClientSocket 程序, 用来测试上面的服务器套接字.

package com.javalearn.socket;

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

public class MyClientSocket {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Socket socket = null;
		PrintWriter out = null;
		try {
			// 客户端套接字 对象
			socket = new Socket("localhost", 8081);
			// 输出流 对象
			out = new PrintWriter(socket.getOutputStream());
			// 输出信息
			String msg = "Fast Fox";
			// 传输
			out.print(msg);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// 资源关闭
			if (out != null) {
				out.close();
			}
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}

}

 

其实下面的测试程序不写也行, 直接在本机的浏览器地址栏输入类似 http://127.0.0.1:8081/index.html 地址后回车即可在控制台看到对应的消息.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值