单人聊天

本文介绍如何使用Java实现客户端与服务器之间的简单通信,包括客户端发起请求、服务器接收并响应的过程。通过实例展示了使用Socket进行网络通信的基本流程,以及如何在服务器端管理多个并发连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package test;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client
{
	private Socket socket = null;
	private class ReceiveThread extends Thread
	{
		@Override
		public void run()
		{
			while (true)
			{
				try
				{
					DataInputStream dis = new DataInputStream(socket.getInputStream());
					String receiveMessage = dis.readUTF();
					System.out.println("客户端发送消息: " + receiveMessage);
				} 
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
	}

	public void start() throws IOException
	{
		socket = new Socket(InetAddress.getByName("localhost"), 7788);
		new ReceiveThread().start();
		System.out.println("已经和服务器建立连接\n请输入你要发送的消息 : ");
		while (true)
		{
			Scanner scaner = new Scanner(System.in);
			String message = scaner.next();
			DataOutputStream dout = new DataOutputStream(socket.getOutputStream());
			dout.writeUTF(message);
			dout.flush();
		}
	}

	public static void main(String[] args) throws IOException
	{
		Client client = new Client();
		client.start();
	}

}

 

package test;
import java.io.*;
import java.net.*;
import java.util.*;
public class Server
{
	private ServerSocket ss   = null;

	private List<Socket> list = new LinkedList<Socket>();

	private class ReceiveThread extends Thread
	{
		private Socket socket = null;

		public ReceiveThread(Socket socket)
		{
			this.socket = socket;
		}

		@Override
		public void run()
		{
			while (true)
			{
				if (socket == null)
				{
					continue;
				}
				try
				{
					DataInputStream dis = new DataInputStream(socket.getInputStream());
					String receiveMessage = dis.readUTF();
					System.out.println("收到客户端发送的消息 :" + socket+ " " + receiveMessage);
					send(receiveMessage);
				} catch (IOException e)
				{
					e.printStackTrace();
				}
			}

		}
	}

	public void send(String msg) throws IOException
	{
		for (int i = 0; i < list.size(); i++)
		{
			Socket groupSocket = list.get(i);
			OutputStream out = groupSocket.getOutputStream();
			DataOutputStream dout = new DataOutputStream(out);
			dout.writeUTF(msg);
			dout.flush();
			out.flush();
		}
	}

	private void start() throws IOException
	{
		ss = new ServerSocket(7788);

		while (true)
		{
			while (true)
			{
				Socket socket = ss.accept();
				list.add(socket);
				new ReceiveThread(socket).start();
			}
		}
	}

	public static void main(String[] args) throws Exception
	{
		System.out.println("服务器开启成功");
		new Server().start();
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值