客户端
package com.csdn.d5_socket2;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Scanner;
public class ClientDemo1 {
public static void main(String[] args) {
System.out.println("===客户端启动===");
Socket socket = new Socket("127.0.0.1", 7777);
OutputStream os = socket.getOutputStream();
PrintStream ps = new PrintStream(os);
Scanner sc = new Scanner(System.in);
System.out.println("请说:");
String msg = sc.nextLine();
} catch (IOException e) {
throw new RuntimeException(e);
服务端
package com.csdn.d5_socket2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
public class ServerDemo2 {
public static void main(String[] args) {
System.out.println("===服务端启动成功===");
ServerSocket serverSocket = new ServerSocket(7777);
Socket socket = serverSocket.accept();
System.out.println(socket.getRemoteSocketAddress() + "它来了,上线了!");
new ServerReaderThread(socket).start();
} catch (IOException e) {
throw new RuntimeException(e);
class ServerReaderThread extends Thread {
public ServerReaderThread(Socket socket) {
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((msg = br.readLine()) != null) {
System.out.println(socket.getRemoteSocketAddress() + "说了:" + msg);
} catch (IOException e) {
System.out.println(socket.getRemoteSocketAddress() + "下线了!!!");