欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-06-06 08:29: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实现服务端与客户端通信

完~