Java使用Socket实现通信

客户端程序

package com.jun.client;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * 〈客户端程序〉
* * @author 未绪 * @time 2018/2/16 12:42 */
public class Client { private Socket socket; public Client(String[] args) { try { socket = new Socket("localhost", 8080); } catch (Exception e) { e.printStackTrace(); } } public void connect() { try { OutputStream out = socket.getOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8"); PrintWriter pw = new PrintWriter(osw, true); BufferedReader brc = new BufferedReader(new InputStreamReader(socket.getInputStream())); Scanner scanner = new Scanner(System.in); while (true) { sendCmdAndGetResult(scanner,brc,pw); } } catch (Exception e) { e.printStackTrace(); } finally { if (socket != null) { try { socket.close(); } catch (Exception e) { e.printStackTrace(); } } } } /** * 向服务器发送数据并获得返回结果 * @param scanner * @param brc * @param pw * @throws IOException */ public void sendCmdAndGetResult(Scanner scanner,BufferedReader brc,PrintWriter pw) throws IOException { pw.println(scanner.nextLine()); String result = brc.readLine(); System.out.println(result); } public static void main(String[] args) { Client client = new Client(args); client.connect(); } }

服务器端程序

package com.jun.server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

/**
 * 〈服务器〉
* * @author 未绪 * @time 2018/2/12 21:06 */
public class ServerMain { private ServerSocket serverSocket; public static void main(String[] args) { ServerMain server= new ServerMain(); server.connect(); //等待连接客户端 } /** * 连接到客户端 */ public void connect(){ try{ serverSocket = new ServerSocket(8080); Socket socket = serverSocket.accept();//阻塞等待客户端的连接 InputStream in = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(in, "UTF-8"); BufferedReader br = new BufferedReader(isr); PrintWriter pw=new PrintWriter(socket.getOutputStream(),true); Scanner scanner = new Scanner(System.in); while(true){ //读取客户端的数据 readCmdAndReturnResult(br,pw,scanner); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 获取客户端传过来的数据并处理数据 * @param br 缓冲流Reader * @param pw 向客户端写数据 * @throws IOException */ public void readCmdAndReturnResult(BufferedReader br,PrintWriter pw,Scanner scanner) throws IOException { String msg=br.readLine(); //读取客户端数据 System.out.println(msg); pw.println(scanner.nextLine()); } }

你可能感兴趣的:([,Java,Java语言基础,])