简单的Java Socket示例

1 篇文章 0 订阅

封装Socket传送类:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

public class SocketWrapper {

	private Socket socket;
	
	private InputStream inputStream;
	
	private BufferedReader inputReader;
	
	private BufferedWriter outputWriter;
	
	public SocketWrapper(Socket socket) throws IOException{
		this.socket = socket;
		this.inputStream = socket.getInputStream();
		this.inputReader = new BufferedReader(
				new InputStreamReader(inputStream, "UTF-8"));
		this.outputWriter = new BufferedWriter(
				new OutputStreamWriter(
						socket.getOutputStream(), "UTF-8"));
	}
	
	public String readLine() throws IOException{
		return this.inputReader.readLine();
	}
	
	public void writeLine(String line) throws IOException{
		this.outputWriter.write(line + '\n');
		this.outputWriter.flush();
	}
	
	public void close(){
		try{
			this.socket.close();
		}catch(Exception e){
			
		}
	}
}


服务端Socket代码:

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

public class SocketServer {

	public static void main(String[] args) throws IOException{
		ServerSocket serSocket = new ServerSocket(8888);
		System.out.println("端口8888已经打开,开始准备接受数据");
		SocketWrapper socket = null;
		try{
			socket = new SocketWrapper(serSocket.accept());
			String line = socket.readLine();
			while(!"bye".equals(line)){
				System.out.println("客户端传来数据:" + line);
				socket.writeLine("我接收到你的数据:" + line);
				line = socket.readLine();
			}
			socket.writeLine("close");
		}finally{
			if(socket != null)socket.close();
		}
	}
}


Socket客户端代码:

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class SocketClient {
	public static void main(String[] args) throws IOException{
		Scanner scanner = new Scanner(System.in);
		SocketWrapper socket = new SocketWrapper(
				new Socket("localhost", 8888));
		try{
			System.out.println("已经连接上服务器,现在可以输入数据开始通信了");
			String sendMsg = scanner.nextLine();
			socket.writeLine(sendMsg);
			String recivedMsg = socket.readLine();
			while(!"close".equals(recivedMsg)){
				System.out.println("===[服务器返回]===>" + recivedMsg);
				sendMsg = scanner.nextLine();
				socket.writeLine(sendMsg);
				recivedMsg = socket.readLine();
			}
			System.out.println("我是客户端,结束了!");
		}finally{
			if(socket != null)socket.close();
		}
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值