Joke Collection Website - Public benefit messages - How does java send a message consisting of string and integer data through TCP?

How does java send a message consisting of string and integer data through TCP?

In Java, you can use Socket and ServerSocket classes to send and receive data through TCP. The following is a simple example showing how to send string and integer data.

First of all, this is a piece of server-side code:

Java copy code

Import java.io. *;

Import java.net. *;

Common class TCPServer {

Public static void main (strinargs []) {

Try {

server socket server socket = new server socket(8080);

System.out.println ("server listening port 8080");

Socket clientsocket = serversocket.accept ();

System.out.println ("connect to the client");

data inputstream in = new data inputstream(client socket . getinputstream());

data output stream out = new data output stream(client socket . get output stream());

string received string = in . read utf();

int received int = in . readint();

system . out . println(" Received string:"+Received string);

system . out . println(" Received int:"+Received int);

Out.writeUTF ("received string");

out . write int(received int * 2);

in . close();

out . close();

client socket . close();

server socket . close();

} catch (IOException e) {

System.out.println ("exception caught while trying to listen to port 8080 or listening to a connection");

System.out.println ("server exception:"+e.getmessage ());

}

}

}

Then, this is a client code:

Java copy code

Import java.io. *;

Import java.net. *;

Common class TCPClient {

Public static void main (strinargs []) {

Try {

Socket Socket = new Socket(" localhost ",8080);

System.out.println ("connect to the server");

data output stream out = new data output stream(socket . get output stream());

data inputstream in = new data inputstream(socket . getinputstream());

out . write utf(" Hello Server ");

out . write int( 123);

string received string = in . read utf();

int received int = in . readint();

system . out . println(" Received string:"+Received string);

system . out . println(" Received int:"+Received int);

in . close();

out . close();

socket . close();

} catch (IOException e) {

System.out.println ("Exception caught while trying to connect to the server");

System.out.println ("client exception:"+e.getmessage ());

}

}

}

In this example, after receiving the string and integer sent by the client, the server will print it out and then return the modified integer. After the client receives the string and integer returned by the server, it will also be printed.