Socket实现服务端与客户端通信

时间:2021-09-19 05:04:23

服务端与客户端都要实现简单接收与发送

1.建立线程用于接收数据

package socket.chat;

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

public class ReceiveThread extends Thread{

	private Socket socket;
	
	public ReceiveThread(Socket socket) {
		this.socket=socket;
	}
	
	public void run() {
		try {
			InputStream inputStream=socket.getInputStream();
			
			DataInputStream dataInputStream=new DataInputStream(inputStream);
			while(true) {
				String message=dataInputStream.readUTF();
				System.out.println("接收:"+message);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

2.建立线程用于发送数据

package socket.chat;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class SendThread extends Thread{

	private Socket socket;
	
	public SendThread(Socket socket) {
		this.socket=socket;
	}
	public void run() {
		try {
			OutputStream outputStream=socket.getOutputStream();
			DataOutputStream dataOutputStream=new DataOutputStream(outputStream);
			
			while(true) {
				Scanner scanner=new Scanner(System.in);
				String str=scanner.next();
				dataOutputStream.writeUTF(str);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

3.建立服务端开启以上两个线程

package socket.chat;

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

public class Server {
	
	public static void main(String[] args) {
		try {
			ServerSocket serverSocket=new ServerSocket(8889);
			
			System.out.println("打开8889端口");
			Socket socket=serverSocket.accept();
			// 启动发送消息线程
			new SendThread(socket).start();
			// 启动接收消息线程
			new ReceiveThread(socket).start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

4.建立客户端开启以上两个线程

package socket.chat;

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

public class Client {
	
	public static void main(String[] args) {
		try {
			Socket socket=new Socket("127.0.0.1", 8889);
			System.out.println("客户端建立socket"+socket.toString());
			// 启动发送消息线程
			new SendThread(socket).start();
			// 启动接收消息线程
			new ReceiveThread(socket).start();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Socket实现服务端与客户端通信

完~