java Socket简单聊天实现

使用Java的Socket实现客户端和服务器端之间的连接,实现客户端重复发送数据到服务器端的功能。即,用户可以在控制台不断输入内容,并将内容逐一发送给服务端。并在服务端显示。

使用到的知识:Socket, Input/OutputStream, Scanner, try...catch, Class

客户端实现:

package TCPUDP;

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class Client {

	private Socket socket;
	
	public Client(){		
			try {
				socket = new Socket("localhost", 8088);			
			} catch (Exception e) {			
				e.printStackTrace();
			}	
	}
	
	public void start(){
		
		try{
			OutputStream out = socket.getOutputStream();
			//OutputStreamWriter osw = new OutputStreamWriter(out, true);
			OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
			PrintWriter pw = new PrintWriter(osw, true);
			//pw.println("你好!服务器!");
			//创建Scanner读取用户输入内容
			Scanner scanner = new Scanner(System.in);
			while(true){
				//scan.nextLine();
				pw.println(scanner.nextLine());
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(socket != null){
				try{
					socket.close();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}				
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Client client = new Client();
		client.start();
	}

}


服务器端实现:
package TCPUDP;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

	private ServerSocket serverSocket;
	
	public Server(){
		try{
			serverSocket = new ServerSocket(8088);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public void start(){
		try{
			System.out.println("等待客户端连接。。。");
			//方法会产生阻塞,直到某个Socket连接,返回请求连接的Socket
			Socket socket = serverSocket.accept();
			System.out.println("客户端已连接!");
			InputStream in = socket.getInputStream();
			InputStreamReader isr = new InputStreamReader(in, "UTF-8");
			BufferedReader br = new BufferedReader(isr);
			//System.out.println("客户端说:" + br.readLine());
			//不断读取客户端数据
			while(true){
				System.out.println("客户端说:" + br.readLine());
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Server server = new Server();
		server.start();
	}

}

©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值