ServerSocket java-server只读输入一次? [英] ServerSocket java-server reads input only once?
问题描述
我写了一个java服务器,这里是代码:
I have written a java server and here is the code:
try
{
ss = new ServerSocket(8080);
while (true)
{
socket = ss.accept();
System.out.println("Acess given");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//out = new PrintWriter(socket.getOutputStream(),true);
line = in.readLine();
System.out.println("you input is :" + in.readLine());
}
}
iphone应用程序是客户端,代码:
And an iphone application is the client and there is the code for it:
- (void)viewDidLoad {
[super viewDidLoad];
socket = [[LXSocket alloc]init];
if ([socket connect:@"10.211.55.2" port:8080]) {
NSLog(@"socket has been created");
}
else {
NSLog(@"socket couldn't be created created");
}
@try {
}@catch (NSException * e) {
NSLog(@"Unable to send data");
}
[super viewDidLoad];
}
-(IBAction)sendData{
[socket sendString:@"A\n"];
}
我在这里有2个问题:首先是服务器只读输入一次。第二个是,当我尝试输出数据时,它不会输出,直到我调用该方法两次(点击uibutton两次)。不知道这里发生了什么。
I am having 2 problems here: first is that the server is only reading the input once. The second is that when ever I try to output the data it doesn't output until I have called the method twice (clicked on the uibutton twice). Not sure what is happening here. What am I doing wrong?
推荐答案
每次在while循环中创建一个新的阅读器。而是将代码移到while循环之外,并在readLine()调用上阻塞。
You are creating a new reader everytime in your while loop. Instead move the code outside the while loop and block on the readLine() call.
socket = ss.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream());
String line = "";
while ( true) {
line = in.readLine();
System.out.println("you input is :" + line);
if ( "Bye".equals(line) )
break;
}
以下是 example 服务器端程序。
这篇关于ServerSocket java-server只读输入一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!