java用ServerSocket类结合io流实现一对一聊天(java实现简单的TCP聊天程序只能用telnet连接后方可使用)

粗略写了点代码,其实这种在流的实现方式里面可以用好多种不同流方面的类,我这没用最简单的,而是那边弄个流这边弄个流,好让自己熟悉不同流的类,希望大家别绕晕哈。可能对新手会有点绕,不过久了应该就会了,代码不唯一,功能达到了就行了,由于时间关系我就没怎么去优化了,代码如下:

本代码是先从服务端向客户端发送消息,然后客户端再向服务端发送,若有一方不回复则不能继续聊天。这是一个简单的类似TCP的聊天程序。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class ServerSocketDemo {
	//一对一发消息
		public static void test3(){
			//服务端
			System.out.println("等待连接中。。。");
			ServerSocket ss;
			try {
				ss = new ServerSocket(6666);
				while(true){
					Socket a = ss.accept();
					System.out.println(a.getInetAddress()+" 已连接成功!");
					OutputStream os = a.getOutputStream();
					PrintWriter pw = new PrintWriter(os);
					pw.write("欢迎来到"+"\r\n");
					pw.write("小询聊天世界"+"\r\n");
					pw.flush();
		//一对一互相发送数据 服务端先发送消息 若有一方不回复则不能继续聊天
					
					Scanner scanner = new Scanner(System.in);
					String wl = null;
					InputStream is = a.getInputStream();
					InputStreamReader isr = new InputStreamReader(is);
					BufferedReader br = new BufferedReader(isr);
					while (scanner.hasNextLine()) {
						String str = scanner.nextLine();
						pw.println("服务端:"+str);
						System.out.println("我:"+str);
						pw.flush();
						String clien = br.readLine();
						System.out.println("客户端:"+clien);
						pw.println("我:"+clien); pw.flush();
					}
				}
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	public static void main(String[] args) {
		test3();
	}
}
运行该代码后可通过两个dos控制台窗口进行聊天,通过telnet IP地址 端口号 命令如 telnet localhost 6666,我是用eclipse作为服务器端和SecureCRT作为客户端进行聊天的。代码演示如下图

运行代码后在eclipse显示如图:


连接CRT后两边的控制台显示如下图:


在服务器端输入聊天内容(您好!我是小询。很高兴认识你。。)回车效果如下图:


在客户端输入内容(我也很高兴认识你。哈哈),效果如下:


可以一直聊下去。。。嘿嘿。。

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我来回答你的问题。 首先,我们需要了解一下 ServerSocketSocket 和 InetAddress 这三个的作用: - ServerSocket:用于监听客户端的连接请求,并创建对应的 Socket 对象进行通信。 - Socket:用于与服务器建立连接并进行通信。 - InetAddress:用于表示 IP 地址。 接下来,我们可以开始编写聊天程序了。下面是一个简单Java 聊天程序的代码: 1. 服务器端代码: ```java import java.io.*; import java.net.*; import javax.swing.*; public class Server extends JFrame { private JTextField userText; private JTextArea chatWindow; private ObjectOutputStream output; private ObjectInputStream input; private ServerSocket server; private Socket connection; // 构造方法 public Server() { super("Server"); userText = new JTextField(); userText.setEditable(false); userText.addActionListener(event -> sendMessage(event.getActionCommand())); add(userText, BorderLayout.NORTH); chatWindow = new JTextArea(); add(new JScrollPane(chatWindow)); setSize(300, 150); setVisible(true); } // 启动服务器 public void startRunning() { try { server = new ServerSocket(7777, 100); while (true) { try { waitForConnection(); setupStreams(); whileChatting(); } catch (EOFException eofException) { showMessage("\nServer ended the connection!"); } finally { closeCrap(); } } } catch (IOException ioException) { ioException.printStackTrace(); } } // 等待连接 private void waitForConnection() throws IOException { showMessage("Waiting for someone to connect...\n"); connection = server.accept(); showMessage("Now connected to " + connection.getInetAddress().getHostName()); } // 设置 private void setupStreams() throws IOException { output = new ObjectOutputStream(connection.getOutputStream()); output.flush(); input = new ObjectInputStream(connection.getInputStream()); showMessage("\nStreams are now setup!\n"); } // 聊天 private void whileChatting() throws IOException { String message = "You are now connected!"; sendMessage(message); ableToType(true); do { try { message = (String) input.readObject(); showMessage("\n" + message); } catch (ClassNotFoundException classNotFoundException) { showMessage("\nUnknown object type received!"); } } while (!message.equals("CLIENT - END")); } // 关闭连接 private void closeCrap() { showMessage("\nClosing connections...\n"); ableToType(false); try { output.close(); input.close(); connection.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } // 发送消息 private void sendMessage(String message) { try { output.writeObject("SERVER - " + message); output.flush(); showMessage("\nSERVER - " + message); } catch (IOException ioException) { chatWindow.append("\nERROR: Cannot send message!"); } } // 更新聊天窗口 private void showMessage(String message) { SwingUtilities.invokeLater(() -> chatWindow.append(message)); } // 是否可以输入 private void ableToType(boolean tof) { SwingUtilities.invokeLater(() -> userText.setEditable(tof)); } } ``` 2. 客户端代码: ```java import java.io.*; import java.net.*; import javax.swing.*; public class Client extends JFrame { private JTextField userText; private JTextArea chatWindow; private ObjectOutputStream output; private ObjectInputStream input; private String message = ""; private String serverIP; private Socket connection; // 构造方法 public Client(String host) { super("Client"); serverIP = host; userText = new JTextField(); userText.setEditable(false); userText.addActionListener(event -> sendMessage(event.getActionCommand())); add(userText, BorderLayout.NORTH); chatWindow = new JTextArea(); add(new JScrollPane(chatWindow)); setSize(300, 150); setVisible(true); } // 连接到服务器 public void startRunning() { try { connectToServer(); setupStreams(); whileChatting(); } catch (EOFException eofException) { showMessage("\nClient terminated the connection!"); } catch (IOException ioException) { ioException.printStackTrace(); } finally { closeCrap(); } } // 连接到服务器 private void connectToServer() throws IOException { showMessage("Attempting connection...\n"); connection = new Socket(InetAddress.getByName(serverIP), 7777); showMessage("Connected to: " + connection.getInetAddress().getHostName()); } // 设置 private void setupStreams() throws IOException { output = new ObjectOutputStream(connection.getOutputStream()); output.flush(); input = new ObjectInputStream(connection.getInputStream()); showMessage("\nStreams are now setup!\n"); } // 聊天 private void whileChatting() throws IOException { ableToType(true); do { try { message = (String) input.readObject(); showMessage("\n" + message); } catch (ClassNotFoundException classNotFoundException) { showMessage("\nUnknown object type received!"); } } while (!message.equals("SERVER - END")); } // 关闭连接 private void closeCrap() { showMessage("\nClosing connections...\n"); ableToType(false); try { output.close(); input.close(); connection.close(); } catch (IOException ioException) { ioException.printStackTrace(); } } // 发送消息 private void sendMessage(String message) { try { output.writeObject("CLIENT - " + message); output.flush(); showMessage("\nCLIENT - " + message); } catch (IOException ioException) { chatWindow.append("\nERROR: Cannot send message!"); } } // 更新聊天窗口 private void showMessage(String message) { SwingUtilities.invokeLater(() -> chatWindow.append(message)); } // 是否可以输入 private void ableToType(boolean tof) { SwingUtilities.invokeLater(() -> userText.setEditable(tof)); } } ``` 以上就是一个使用 ServerSocket Socket 以及 InetAddress 编写的简单聊天程序的代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值