java 网络服务器_java – 客户端 – 服务器网络入门

我更喜欢Java.我要解释一下TCP:

基本概念是您必须在机器上运行“服务器”.该服务器接受等待连接的客户端.每个连接都通过一个端口(你知道,我希望…).

始终使用高于1024的端口,因为低于1025的端口大部分时间保留用于标准协议(如HTTP(80),FTP(21),Telnet,…)

但是,使用Java创建服务器是这样做的:

ServerSocket server = new ServerSocket(8888); // 8888 is the port the server will listen on.

“Socket”是你想要研究的词,你可能会寻找.

并将您的客户端连接到服务器,您必须写下这个:

Socket connectionToTheServer = new Socket("localhost",8888); // First param: server-address,Second: the port

但是现在还没有连接.服务器必须接受等待的客户端(正如我在上面注意到的):

Socket connectionToTheClient = server.accept();

完成!您的连接建立!通信就像File-IO.您唯一需要记住的是,您必须决定何时刷新缓冲区,并通过套接字发送数据.

使用PrintStream进行文本写作非常方便:

OutputStream out = yourSocketHere.getOutputStream();

PrintStream ps = new PrintStream(out,true); // Second param: auto-flush on write = true

ps.println("Hello,Other side of the connection!");

// Now,you don't have to flush it,because of the auto-flush flag we turned on.

一个BufferedReader的文本阅读是好的(最好的*)选项:

InputStream in = yourSocketHere.getInputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(in));

String line = br.readLine();

System.out.println(line); // Prints "Hello,Other side of the connection!",in this example (if this would be the other side of the connection.

希望您可以从这个信息网络开始!

PS:当然,所有的网络代码都必须尝试IOExceptions.

编辑:我忘了写为什么并不总是最好的选择. BufferedReader使用缓冲区,并尽可能多地读入缓冲区.但有时你不希望BufferedReader在换行符之后窃取字节,并将它们放入自己的缓冲区.

简短的例子:

InputStream in = socket.getInputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(in));

// The other side says hello:

String text = br.readLine();

// For whatever reason,you want to read one single byte from the stream,// That single byte,just after the newline:

byte b = (byte) in.read();

但是BufferedReader已经有这个字节,你想在他的缓冲区中读取.所以调用in.read()将返回读取器缓冲区中最后一个字节的后面的字节.

所以,在这种情况下,最好的解决方案是使用DataInputStream并管理它自己的方式来知道字符串将要多长时间,只读这个字节数并将其转换为一个字符串.或者:你使用

DataInputStream.readLine()

该方法不使用缓冲区,逐字节读取并检查换行符.所以这种方法不会从底层的InputStream中窃取字节.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值