ServerSocket java

编程入门 行业动态 更新时间:2024-10-24 20:16:07
本文介绍了ServerSocket java-server只读输入一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我写了一个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

本文发布于:2023-11-09 10:14:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572107.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:ServerSocket   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!