码迷,mamicode.com
首页 > 编程语言 > 详细

java中TCP之TCP实现

时间:2015-09-26 14:35:04      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

java中TCP之TCP实现

代码均来自计算机网络教材


此为服务器端代码

  1. package server;
  2. import java.io.BufferedReader;
  3. import java.io.DataOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.net.ServerSocket;
  7. import java.net.Socket;
  8. public class TcpServer {
  9. public static void main(String[] args) throws IOException {
  10. String getString;
  11. String sendString;
  12. ServerSocket socket = new ServerSocket(6789);
  13. //ServerSocket 为服务器监听的类
  14. while(true) {
  15. //收到accept请求,返回socket实例
  16. Socket connection = socket.accept();
  17. System.out.println("connect successfully");
  18. //获得输入的内容,即客户端程序发送过来的消息
  19. BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  20. //发送回去的内容
  21. DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
  22. getString = reader.readLine();
  23. sendString = getString.toUpperCase() + "\n";
  24. //将内容写入到想要返回给客户端的流中
  25. outputStream.writeBytes(sendString);
  26. }
  27. }}

client类
package client;

  1. import java.io.BufferedReader;
  2. import java.io.DataOutputStream;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.net.Socket;
  6. import java.net.UnknownHostException;
  7. import java.nio.Buffer;
  8. public class TcpClient {
  9. public static void main(String[] args) throws UnknownHostException, IOException {
  10. // TODO Auto-generated method stub
  11. String sendString;
  12. String getString;
  13. BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
  14. System.out.println("start connection");
  15. //开始连接,参数为host,如果为本地的话,则为127.0.0.1,端口跟服务器使用端口相同
  16. Socket socket = new Socket("45.62.102.41", 6789);
  17. System.out.println("connect successfully");
  18. //发送的内容
  19. DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
  20. //接收的内容
  21. BufferedReader fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  22. sendString = bufferedReader.readLine();
  23. outputStream.writeBytes(sendString + "\n");
  24. getString = fromServer.readLine();
  25. System.out.print(getString);
  26. socket.close();
  27. }}

可以看到,这个连接是能够确保数据的传输的.在传输数据之前,我们新建了一个虚拟通道(从socket到ServerSocket之间的),并且我们可以通过数据流来进行数据的传输.





java中TCP之TCP实现

标签:

原文地址:http://www.cnblogs.com/wilbertwu/p/4840663.html

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