码迷,mamicode.com
首页 > 其他好文 > 详细

tcp 客户服务端

时间:2017-07-03 12:07:36      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:flush   logs   eth   case   stream   while   tin   java.net   res   


 1

package TCP;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

public static void main(String[] args) throws IOException {
//创建socket对象
ServerSocket serversocket = new ServerSocket(5555);
System.out.println("服务端启动!");
//接收客户端请求
Socket socket = serversocket.accept();
System.out.println(socket.getInetAddress().getHostAddress()+"连接成功");
//接收字节
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// //发送字节
// BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//输入输出流 可选择 true自动刷新缓冲区
PrintWriter pw = new PrintWriter(socket.getOutputStream(),true);

String line = null;
//读取客户端传的信息
while((line = br.readLine())!=null){
if(line.equals("over")){
break;
}
System.out.println(line);
//转换成大写发送

pw.println(line.toUpperCase());

// bw.write(line.toUpperCase());
// //换行
// bw.newLine();
// //清空缓冲区 强制发送
// bw.flush();
}

pw.close();
//bw.close();
br.close();
socket.close();
serversocket.close();
System.out.println("退出成功");
}

}

 

 

 1 package TCP;
 2 
 3 import java.io.BufferedReader;
 4 import java.io.BufferedWriter;
 5 import java.io.IOException;
 6 import java.io.InputStreamReader;
 7 import java.io.OutputStreamWriter;
 8 import java.net.ServerSocket;
 9 import java.net.Socket;
10 
11 public class Server {
12 
13     public static void main(String[] args) throws IOException {
14         //创建socket对象
15         ServerSocket serversocket = new ServerSocket(5555);
16         System.out.println("服务端启动!");
17         //接收客户端请求
18         Socket socket =  serversocket.accept();
19         System.out.println(socket.getInetAddress().getHostAddress()+"连接成功");
20         //接收字节
21         BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
22         //发送字节
23         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
24         String line = null;
25         //读取客户端传的信息
26 while((line = br.readLine())!=null){
27     if(line.equals("over")){
28         break;
29     }
30     System.out.println(line);
31     //转换成大写发送
32     bw.write(line.toUpperCase());
33     //换行
34     bw.newLine();
35     //清空缓冲区 强制发送
36     bw.flush();
37 }
38 br.close();
39 bw.close();
40 socket.close();
41 serversocket.close();
42 System.out.println("退出成功");
43     }
44 
45 }

 

tcp 客户服务端

标签:flush   logs   eth   case   stream   while   tin   java.net   res   

原文地址:http://www.cnblogs.com/the-wang/p/7109691.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!