集册 Java实例教程 使用服务器套接字接受文本

使用服务器套接字接受文本

欢马劈雪     最近更新时间:2020-01-02 10:19:05

466
使用服务器套接字接受文本

import java.io.*;

import java.net.*;


class TCPServer {//N o w J a v a . c o m 提供

     public static void main(String args[]) throws IOException {

          String clientSentence ;

          String capitalizedSentence;

          ServerSocket ws = new ServerSocket(1234);

          ws.setSoTimeout(15000); // Setting the timeout time to 15 seconds.


          boolean connection = true; // Connection flag.


          while(connection)

          {/**来自 时   代    Java - nowjava.com**/

               try {

                    Socket cs = ws.accept();

                    System.out.println("Connected to Client"); // Log if connected.

                    BufferedReader inFromClient = new BufferedReader(new InputStreamReader(cs.getInputStream()));

                    DataOutputStream outToClient = new DataOutputStream(cs.getOutputStream());

                    clientSentence = inFromClient.readLine();

                    capitalizedSentence = clientSentence.toUpperCase() + "\n";

                    outToClient.writeBytes(capitalizedSentence);

                    System.out.println("Msg sent");

 
展开阅读全文