TCP套接字编程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Armstrong_rose/article/details/79968527

Java C/S程序

  • client从标准输入读取一行字符,通过socket发送到服务器
  • server从socket读取一行字符,转换成大写
  • 修改后的字符返回client,打印输出

TCPClient.java

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class TCPClient {
    public static void main(String[] args) throws Exception{

        String sentence;//用户输入的字符串,送到服务器
        String modifiedSentence;//从服务器得到,送到用户标准输出

        //创建流,可从键盘读入文本
        BufferedReader inFromUser = new BufferedReader(
                new InputStreamReader(System.in));

        //socket对象,发起客户端和服务器之间的tcp连接
        Socket clientSocket = new Socket("127.0.0.1", 6789);

        //为进程提供了到套接字的输出
        DataOutputStream outToServer = new DataOutputStream(
                clientSocket.getOutputStream());
        //为进程提供了来自套接字的输入
        BufferedReader inFromServer = new BufferedReader(
                new InputStreamReader(clientSocket.getInputStream()));

        sentence = inFromUser.readLine();
        outToServer.writeBytes(sentence + '\n');

        modifiedSentence = inFromServer.readLine();
        System.out.println("From Server:" + modifiedSentence);

        clientSocket.close();
    }
}

TCPServer.java

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {
    public static void main(String[] args) throws Exception {
        String clientSentence;
        String capitalizedSentence;
        //创建ServerSocket对象,在6789端口上监听
        ServerSocket welcomeSocket = new ServerSocket(6789);

        while (true) {
            Socket connectionSocket = welcomeSocket.accept();
            BufferedReader inFromClient = new BufferedReader(
                    new InputStreamReader(connectionSocket.getInputStream()));
            DataOutputStream outToClient = new DataOutputStream(
                    connectionSocket.getOutputStream());
            clientSentence = inFromClient.readLine();

            capitalizedSentence = clientSentence.toUpperCase() + '\n';
            outToClient.writeBytes(capitalizedSentence);

        }
    }
}

运行结果

xuebibi
From Server:XUEBIBI
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页