我正在尝试创建一个简单的client/server socket app
。我遇到的问题是如何制作,我应该把它放在哪里,一部分将在客户端询问输入,然后在服务器端打印出相同的输入。我试过但没有成功。
GOAL :在Client类的控制台中,当用户输入例如"我的名字是Mike"时,我想要的是当时在Server的控制台上字符串"我的名字是Mike"打印出新的一行。
主要
public class Main {
public static void main(String[] args) {
System.out.println("The server has been summoned.\n");
System.out.println("The server is waiting for client to come...");
try {
ServerSocket servertest = new ServerSocket(2014);
while (true) {
try {
Socket ser = servertest.accept();
new Server.ThreadSer(ser).start();
} catch (IOException e) {}
}
} catch (IOException e) {System.err.println(e);}
}}}
服务器
public class Server {
public static class ThreadSer extends Thread {
private Socket s;
public ThreadSer(Socket s) {
this.s = s;
}
@Override
public void run() {
try {
String response = "This is the IP: " + s.getLocalAddress() + " that has come via port: "
+ s.getLocalPort() + "\r\n";
OutputStream out = s.getOutputStream();
out.write(response.getBytes());
} catch (IOException e) { System.err.println(e); }
}}}
客户端
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("localhost", 2014);
new OutputThread(socket.getInputStream()).start();
}
public static class OutputThread extends Thread {
private InputStream inputstream;
public OutputThread(InputStream inputstream) {
this.inputstream = inputstream;
}
@Override
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(inputstream));
while (true) {
try {
String line = input.readLine();
System.out.println(line);
} catch (IOException exception) {
exception.printStackTrace();
break;
}}}}}
我在代码中遗漏了一些内容。
答案 0 :(得分:2)
在您的客户端中,您不需要从输出流所需的服务器读取线路以将字符串发送到服务器:
示例:
客户 中的
: public static class OutputThread extends Thread {
private InputStream inputstream;
Scanner scanner;
String message;
public OutputThread(OutputStream outputstream) {
this.inputstream = inputstream;
}
@Override
public void run() {
ObjectOutputStream output = new ObjectOutputStream(outputstream);
scanner = new Scanner(System.in);
while (true) {
try {
System.out.print("InputMessage: ");
message = scanner.nextLine();
System.out.println(message);
output.writeObject(message); //send the string to the server
output.flush();
} catch (IOException exception) {
exception.printStackTrace();
break;
}}}}}
服务器中 public class Server {
public static class ThreadSer extends Thread {
private Socket s;
public ThreadSer(Socket s) {
this.s = s;
}
@Override
public void run() {
try {
String response = "This is the IP: " + s.getLocalAddress() + " that has come via port: "
+ s.getLocalPort() + "\r\n";
ObjectInputStream input = new ObjectInputStream(s.getInputStream());
while(true){
Object object = input.readObject();
String command = ((String) object).trim(); //trim the string
System.out.println(command);
}
} catch (IOException e) { System.err.println(e); }
}}}