JAVA客户端错误,Java客户端/服务器读取和写入不起作用,也没有错误

Client.java

package Client;

import java.io.*;

import java.net.*;

class Client {

/*

To send string to server use "out.print(data)"

To use info sent from server use "in.readLine()"

*/

int port = 1234;

String hostname = "localhost";

String input,output;

public void send(String text) {

try {

Socket skt = new Socket(hostname, port); /*Connects to server*/

BufferedReader in = new BufferedReader(new

InputStreamReader(skt.getInputStream())); /*Reads from server*/

System.out.println("Server:" + in.readLine());

PrintWriter out = new PrintWriter(skt.getOutputStream(), true);

out.print(text); /*Writes to server*/

skt.close();

out.close(); /*Closes all*/

in.close();

}

catch(Exception e) {

System.out.print("Error Connecting to Server\n");

}

}

public static void main(String args[]) {

Client c = new Client();

c.send("Server is online"); //sends message to server

}

}

Server.java

package Server;

import java.io.*;

import java.net.*;

class Server {

/*

To send string to client use "out.print(data)"

To use info sent from client use "in.readLine()"

*/

int port = 1234;

String input,output;

public void send(String text) {

try {

ServerSocket srvr = new ServerSocket(port);

Socket skt = srvr.accept(); /*Waiting for Connection from client*/

System.out.print("Server has connected!\n");

PrintWriter out = new PrintWriter(skt.getOutputStream(), true);

out.print(text); /*Write/Send to Client*/

BufferedReader in = new BufferedReader(new

InputStreamReader(skt.getInputStream())); /*Read from Client*/

System.out.println("Client:" + in.readLine());

out.close();

in.close();

skt.close(); /*Closes all*/

srvr.close();

} catch( Exception e) {

System.out.print("Error Connecting\n");

}

}

public static void main(String args[]) {

Server s = new Server();

s.send("Client is online"); //sends a message to client

}

}

why does nothing apart from

Server has connected!

happen when on both I have sent from the server and client

s.send("X is online");

which should be read on the other side and printed out in the cmd?

(is it because the bufferreader is activated after printwriter and doesn't pick it up? if so how can I fix this?)

解决方案

Your BufferedReader#readLine call will block indefinitely unless you send a newline character. Replace

out.print(text);

with

out.println(text);

to match the BufferedReader#readLine calls from both client & server.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值