提问人:melodic_n 提问时间:11/12/2023 更新时间:11/12/2023 访问量:24
在服务器和客户端套接字之间发送字符串 [已关闭]
Sending strings between a server and client socket [closed]
问:
所以我们刚刚开始学习 java 中的客户端-服务器架构,TBH 我对一些东西有点困惑,但是当我们用数字测试它时,我理解了过程是如何工作的以及每个对象的作用,但是当教授要求我们发送字符串时,当我看到我们必须使用的新库和对象时,我的大脑停止了:
- 缓冲阅读器
- 印刷作家
- 输入流读器
我不明白这些库中的任何一个的作用,但我已经尝试过:
import java.net.InetAddress;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStreamReader;
public class Client {
private static String username ;
static String msg;
public static void main(String[] args) {
try {
InetAddress ip = InetAddress.getByName("127.0.0.1");
Socket SClient = new Socket(ip,6020);
InputStream recieve = SClient.getInputStream();
OutputStream send = SClient.getOutputStream();
InputStreamReader in = new InputStreamReader(recieve);
BufferedReader br = new BufferedReader(in);
PrintWriter pw = new PrintWriter(send,true);
Scanner input = new Scanner(System.in);
String Smsg =br.readLine();
System.out.println(Smsg);
System.out.println(" enter your username : ");
username=input.nextLine();
//msg=input.nextLine();
pw.print(username);
//pw.write(msg);
}
public class Serveur {
public static void main(String[] args) {
String msg_rec;
String user;
try {
ServerSocket ss = new ServerSocket(6020);
System.out.println("server lancer sur l ip " + ss.getLocalSocketAddress() +" and port number "+ss.getLocalPort());
Socket sc=ss.accept();
InputStream recieve = sc.getInputStream();
OutputStream send = sc.getOutputStream();
InputStreamReader in = new InputStreamReader(recieve);
BufferedReader br = new BufferedReader(in);
PrintWriter pw = new PrintWriter(send,true);
pw.print("hello");
String smsg,rmsg;
while(true) {
smsg = br.readLine();
pw.println(smsg);
}
}
答: 暂无答案
评论