socket编程实现简单的单线程聊天室

客户端:

package single;

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

public class SingleThreadClient {
    public static void main(String[] args) throws IOException {
        //建立连接
        Socket socket=new Socket("127.0.0.1",6666);

        //进行数据输入输出,先发送再接收
        PrintStream printStream=new PrintStream(socket.getOutputStream(),true,"UTF-8");
        Scanner in =new Scanner(System.in);
        String str="";
        System.out.println("请输入向服务器发送的信息......");
        if(in.hasNext()){
            str=in.nextLine();
        }
        Scanner scanner=new Scanner(socket.getInputStream());
        if(scanner.hasNext()){
            System.out.println("从服务器端发来的信息为:"+scanner.nextLine());
        }

        printStream.println("hello.i am client");
        //关闭流
        scanner.close();
        printStream.close();
        socket.close();
    }

}

服务器:

package single;

import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class SingleThreadServer {
    public static void main(String[] args) throws IOException {
        //建立基站
        ServerSocket server =new ServerSocket(6666);
        //等待客户端连接
        System.out.println("正在等待客户端连接......");
        Socket socket=server.accept();//两根线
        //3.建立连接后进行数据的输入输出
        //服务器给客户端输出流,输出用打印流,输入用scanner类
        PrintStream  printStream=new PrintStream(socket.getOutputStream(),true,"UTF-8");//自动// 刷新
        printStream.println("hello i am server");
        Scanner scanner=new Scanner(socket.getInputStream());
        if(scanner.hasNext()){
            System.out.println("客户端发送过来的信息为:"+scanner.nextLine());
        }
        //关闭流
        scanner.close();
        printStream.close();
        server.close();

    }
}

先运行服务器,再运行客户端

socket编程实现简单的单线程聊天室_第1张图片
socket编程实现简单的单线程聊天室_第2张图片

你可能感兴趣的:(socket编程实现简单的单线程聊天室)