标签:
代码均来自计算机网络教材
此为服务器端代码
package server;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServer {
public static void main(String[] args) throws IOException {
String getString;
String sendString;
ServerSocket socket = new ServerSocket(6789);
//ServerSocket 为服务器监听的类
while(true) {
//收到accept请求,返回socket实例
Socket connection = socket.accept();
System.out.println("connect successfully");
//获得输入的内容,即客户端程序发送过来的消息
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
//发送回去的内容
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
getString = reader.readLine();
sendString = getString.toUpperCase() + "\n";
//将内容写入到想要返回给客户端的流中
outputStream.writeBytes(sendString);
}
}}
client类
package client;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.Buffer;
public class TcpClient {
public static void main(String[] args) throws UnknownHostException, IOException {
// TODO Auto-generated method stub
String sendString;
String getString;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("start connection");
//开始连接,参数为host,如果为本地的话,则为127.0.0.1,端口跟服务器使用端口相同
Socket socket = new Socket("45.62.102.41", 6789);
System.out.println("connect successfully");
//发送的内容
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
//接收的内容
BufferedReader fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
sendString = bufferedReader.readLine();
outputStream.writeBytes(sendString + "\n");
getString = fromServer.readLine();
System.out.print(getString);
socket.close();
}}
可以看到,这个连接是能够确保数据的传输的.在传输数据之前,我们新建了一个虚拟通道(从socket到ServerSocket之间的),并且我们可以通过数据流来进行数据的传输.
标签:
原文地址:http://www.cnblogs.com/wilbertwu/p/4840663.html