前言:以前写的一个Socket实现一对一通信的例子
ClientDemo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.util.Scanner;
public class ClientDemo { public void ClientSocket(){ System.out.println("向服务器请求连接中"); Socket socket; Scanner keybordScanner,inScanner; PrintWriter printWriter; try { socket = new Socket("127.0.0.1", 21412); inScanner = new Scanner(socket.getInputStream()); System.out.println(inScanner.nextLine()); printWriter = new PrintWriter(socket.getOutputStream());
System.out.print("客户端:"); keybordScanner = new Scanner(System.in); while(keybordScanner.hasNextLine()){ String keybordData = keybordScanner.nextLine(); printWriter.println(keybordData); printWriter.flush(); System.out.println("服务端:"+inScanner.nextLine()); System.out.print("客户端:"); } socket.close(); keybordScanner.close(); printWriter.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new ClientDemo().ClientSocket(); } }
|
ServerDemo
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner;
public class ServerDemo { public void ServerSocket(){ System.out.println("等待客户端连接中"); PrintWriter printWriter; Scanner keybordScanner,inScanner; ServerSocket serverSocket; try { serverSocket = new ServerSocket(21412); Socket socket = serverSocket.accept(); System.out.println("已成功连接到"+socket.getInetAddress()+"服务器上"); printWriter = new PrintWriter(socket.getOutputStream()); printWriter.println("已成功连接到远程服务器!"+"\t"+"请您先发言。"); printWriter.flush(); keybordScanner = new Scanner(System.in); inScanner = new Scanner(socket.getInputStream()); while(inScanner.hasNextLine()){ System.out.println("客户端:" + inScanner.nextLine()); System.out.print("服务端:"); printWriter.println(keybordScanner.nextLine()); printWriter.flush(); } serverSocket.close(); printWriter.close(); keybordScanner.close(); inScanner.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new ServerDemo().ServerSocket(); } }
|