import java.io.InputStream;
安顺ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18980820575(备注:SSL证书合作)期待与您的合作!
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.util.Date;
class Server
{
public Server()
{
try
{
ServerSocket s=new ServerSocket(8888);
Socket ss=s.accept();
OutputStream out=ss.getOutputStream();
DataOutputStream dout=new DataOutputStream(out);
InputStream in=ss.getInputStream();
DataInputStream din=new DataInputStream(in);
System.out.print(din.readUTF()+"!");
dout.writeUTF("你已经连接到服务器"+"\t"+"你的地址:"+ss.getInetAddress()+"\t"
+"你的链接端口:"+ss.getLocalPort()+"\n");
new ReadMessage(din).start();
new SendMessage(dout).start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new Server();
}
}
//接受客户端信息
class ReadMessage extends Thread
{
private DataInputStream din;
public ReadMessage(DataInputStream din)
{
this.din=din;
}
public void run()
{
String str;
try
{
while (true)
{
str=din.readUTF();
System.out.println(new Date().toLocaleString()+"客户端说:"+str);
if (str.equals("bye"))
{
System.out.println("客户端下线!");
break;
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
// 发出服务器信息
class SendMessage extends Thread
{
private DataOutputStream dout;
public SendMessage(DataOutputStream dout)
{
this.dout=dout;
}
public void run()
{
InputStreamReader inr=new InputStreamReader(System.in);
BufferedReader buf=new BufferedReader(inr);
String str;
try
{
while(true)
{
str=buf.readLine();
dout.writeUTF(str);
if (str.equals("bye"))
{
System.out.println("服务器退出!");
System.exit(1);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
import java.io.InputStream;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.net.Socket;
import java.io.IOException;
import java.util.Date;
class Client
{
public Client()
{
try
{
Socket s=new Socket("192.168.1.2",8888);
InputStream in=s.getInputStream();
DataInputStream din=new DataInputStream(in);
OutputStream out=s.getOutputStream();
DataOutputStream dout=new DataOutputStream(out);
dout.writeUTF("服务器你好!我是客户端");
System.out.println(din.readUTF());
new Thread(new SenderMessage(dout)).start();
new Thread(new ReaderMessage(din)).start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new Client();
}
}
class ReaderMessage implements Runnable
{
private DataInputStream din;
public ReaderMessage(DataInputStream din)
{
this.din=din;
}
public void run()
{
String str;
try
{
while(true)
{
str=din.readUTF();
System.out.println(new Date().toLocaleString()+"服务器说:"+str);
if (str.equals("bye"))
{
System.out.println("服务器已经关闭,此程序自动退出!");
break;
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
class SenderMessage implements Runnable
{
private DataOutputStream dout;
public SenderMessage(DataOutputStream dout)
{
this.dout=dout;
}
public void run()
{
String str;
InputStreamReader inf=new InputStreamReader(System.in);
BufferedReader buf=new BufferedReader(inf);
try
{
while (true)
{
str=buf.readLine();
dout.writeUTF(str);
if (str.equals("bye"))
{
System.out.println("客户端自己退出!");
System.exit(1);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
public class ChatFrame extends JPanel{
private static final long serialVersionUID = 1L;
private int width=450,height=450;
boolean flag;
int port = 10086;
String address = "192.168.33.52";
// int port = 2425;
DatagramSocket send;
DatagramSocket receive;
UDP_Send udpSend;
JTextArea showTextArea;
JTextArea inputTextArea;
JPanel rightPanel;
JScrollPane scrollPane1;
JScrollPane scrollPane2;
JSplitPane splitPane1;
JSplitPane splitPane2;
JButton sendButton;
JButton closeButton;
JPanel buttonpane;
public ChatFrame() throws Exception {
super(null, true);
send = new DatagramSocket();
receive = new DatagramSocket(port);
udpSend =new UDP_Send(send,port);
showTextArea = new JTextArea();
showTextArea.setLineWrap(true);
showTextArea.setEditable(false);
showTextArea.setForeground(new Color(0xf90033));
scrollPane1 = new JScrollPane(showTextArea);
inputTextArea = new JTextArea();
inputTextArea.setLineWrap(true);
scrollPane2 = new JScrollPane(inputTextArea);
rightPanel = new JPanel();
rightPanel.setBackground(new Color(0x0099ff));
splitPane1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,true,scrollPane1,scrollPane2);
splitPane2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,splitPane1,rightPanel);
inputTextArea.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_ENTER:
udpSend.send(port);
inputTextArea.setText("");
break;
default:
break;
}
}
});
sendButton = new JButton("发送");
sendButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
udpSend.send(port);
inputTextArea.setText("");
}
});
closeButton = new JButton("关闭");
closeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
buttonpane = new JPanel();
buttonpane.add(closeButton);
buttonpane.add(sendButton);
splitPane1.setBounds(0, 0, width, height-32);
splitPane1.setDividerLocation(0.8);
splitPane2.setBounds(0, 0, width, height-32);
splitPane2.setDividerLocation(0.8);
buttonpane.setBounds(width-250, height-32, 140, 32);
this.add(splitPane2);
this.add(buttonpane);
this.setPreferredSize(new Dimension(width,height));
new Thread(new UDP_Receive(receive)).start();
}
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame();
frame.setContentPane(new ChatFrame());
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
class UDP_Send{
DatagramSocket datagramSocket;
int port;
String text;
public UDP_Send(DatagramSocket datagramSocket,int port) {
this.datagramSocket = datagramSocket;
this.port = port;
}
public void send(int port) {
try {
text = new String(inputTextArea.getText().getBytes(), "utf-8");
byte buffered[] = text.getBytes();
DatagramPacket database = new DatagramPacket(buffered,
buffered.length, InetAddress.getByName(address),port) ;
showTextArea.setFont(new Font("微软雅黑", Font.CENTER_BASELINE, 24));
showTextArea.append("本机"+":\n");
showTextArea.setFont(new Font("仿宋", Font.CENTER_BASELINE, 16));
showTextArea.append(" "+text+"\n");
datagramSocket.send(database);
} catch (IOException e) {
e.printStackTrace();
}
}
}
class UDP_Receive implements Runnable {
DatagramSocket datagramSocket;
public UDP_Receive(DatagramSocket datagramSocket) {
this.datagramSocket = datagramSocket;
}
@Override
public void run() {
try {
byte buff[] = new byte[4096];
DatagramPacket database = new DatagramPacket(buff, buff.length);
while (true) {
datagramSocket.receive(database);
String text = new String(database.getData(), 0,database.getLength(),"utf-8");
showTextArea.setFont(new Font("微软雅黑", Font.CENTER_BASELINE, 24));
showTextArea.append(database.getAddress()+":\n");
showTextArea.setFont(new Font("仿宋", Font.CENTER_BASELINE, 16));
showTextArea.append(" "+text+"\n");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Java 实现聊天室可以分为以下几个步骤:
建立服务器端
首先需要建立一个服务器端,负责接收客户端的连接请求并处理客户端发送过来的消息。
建立客户端
然后需要建立客户端,客户端通过网络连接到服务器端,并向服务器端发送消息。
实现通信协议
为了实现聊天室功能,需要定义一个通信协议,规定客户端和服务器端之间的通信格式,例如消息的头部和内容等。
实现多线程处理
聊天室通常会有多个用户同时在线,因此需要使用多线程来处理多个客户端的连接请求和消息传递。
实现GUI界面(可选)
为了方便用户使用,可以实现一个GUI界面,让用户可以方便地发送和接收消息。
以下是一个简单的 Java 聊天室的代码示例:
java
Copy code
// 服务器端代码
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
while (true) {
Socket socket = serverSocket.accept();
new Thread(new ServerThread(socket)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerThread implements Runnable {
private Socket socket;
private BufferedReader reader;
private PrintWriter writer;
public ServerThread(Socket socket) {
this.socket = socket;
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
String msg;
while ((msg = reader.readLine()) != null) {
// 处理客户端发送过来的消息
System.out.println("接收到消息:" + msg);
// 将消息发送给所有客户端
for (Socket s : ServerThreadList.getList()) {
if (s != socket) {
PrintWriter w = new PrintWriter(s.getOutputStream());
w.println(msg);
w.flush();
}
}
}
// 关闭连接
socket.close();
ServerThreadList.removeThread(this);
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerThreadList {
private static List
list = new ArrayList();
public static void addThread(ServerThread thread) {
list.add(thread);
}
public static void removeThread(ServerThread thread) {
list.remove(thread);
}
public static List
getList() {
return list;
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
new Thread(new ClientThread(socket)).start();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(socket.getOutputStream());
while (true) {
String msg = reader.readLine();
writer.println(msg);
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ClientThread implements Runnable {
private Socket socket;
private BufferedReader reader;
public ClientThread(Socket socket) {
this.socket = socket;
try {
reader