TCP实现服务器与单客户端连接(多线程)

局域网内实现单客户端与服务器通信

客户端通过配置ip和端口号来连接服务器

客户端和服务器端各自具有发送和接收线程,可以实现一方持续发送

服务器端

package Net;

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

public class Server2 {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket=new ServerSocket(9999);
        System.out.println("服务器已启动等待连接");
        Socket socket=serverSocket.accept();
        System.out.println("连接成功");
        In in=new In(socket,"张三");
        Out out=new Out(socket);
        in.start();
        out.start();
    }
}

客户端

package Net;

import java.io.IOException;
import java.net.Socket;

public class Client2 {
    public static void main(String[] args) throws IOException {
        Socket socket=new Socket("127.0.0.1",9999);
        if(socket.isConnected()){
            System.out.println("连接成功");
        }
        In in=new In(socket,"张修");
        Out out=new Out(socket);
        in.start();
        out.start();
    }
}

输入线程

package Net;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class In extends Thread{
    Socket socket;
    String name;
    public In(Socket socket){
        this.socket=socket;
    }
    public In(Socket socket,String name){
        this.socket=socket;
        this.name=name;
    }
    @Override
    public void run() {
        InputStream inputStream= null;
        try {
            inputStream = socket.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        DataInputStream din=new DataInputStream(inputStream);
        while(true){
            try {
                String ss=din.readUTF();
                System.out.println(name+":"+ss);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

输出线程

package Net;

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

public class Out extends Thread{
    Socket socket;
    String name;
    public Out(Socket socket){
        this.socket=socket;
    }
    @Override
    public void run() {
        OutputStream out = null;
        try {
            out = socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        DataOutputStream dout = new DataOutputStream(out);
        Scanner scanner=new Scanner(System.in);
        while(true){
            String s= scanner.next();
            try {
                dout.writeUTF(s);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

测试

开启服务器端

TCP实现服务器与单客户端连接(多线程)_第1张图片

开启客户端

TCP实现服务器与单客户端连接(多线程)_第2张图片

TCP实现服务器与单客户端连接(多线程)_第3张图片

开始聊天

TCP实现服务器与单客户端连接(多线程)_第4张图片 

TCP实现服务器与单客户端连接(多线程)_第5张图片 

 

 

 

你可能感兴趣的:(javase代码,服务器,tcp/ip,网络)