A simple example with Socket

A simple example with Socket

Concepts:

  1. socket:

  2. thread

  3. I/O stream

    Output stream -> Sending buffer queue (SendQ)-> Network

    Network-> Receiving buffer queue (RecvQ)->Input Stream

Example:

Write a net program, include a server and client, client will send a string to the server, and server should print the string to the terminal, and return the length of string to the client, and finally the client should print the length sent from server. You should do it in TCP and UDP way.

Code:

TCP Client

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.io.*;
import java.net.Socket;
public class TCPClient {
public static void main(String args[]) throws Exception{
Socket socket = new Socket("127.0.0.1",65000);
OutputStream os = socket.getOutputStream();
InputStream is = socket.getInputStream();
os.write(new String("xxx").getBytes());
int ch = 0;
byte [] buff = new byte[1024];
ch = is.read(buff);
String content = new String(buff,0,ch);
System.out.println(content);
is.close();
os.close();
socket.close();

}
}

TCP Server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.net.ServerSocket;
import java.net.Socket;
import java.util.SortedSet;

public class TCPServer {
public static void main(String args[]) throws Exception{
//create and bind port
ServerSocket ss = new ServerSocket(65000);
//dead loop awaiting client sending request
while(true){
Socket socket = ss.accept();
//only start after accept the require from client
new LengthCalculator(socket).start();

}

}

}

Length Calculator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.io.*;

import java.net.Socket;

public class LengthCalculator extends Thread{
private Socket socket;

public LengthCalculator(Socket socket){
this.socket = socket;
}

public void run(){
try{
//output stream
OutputStream os = socket.getOutputStream();
//input stream
InputStream is = socket.getInputStream();
//ch for reading string length
int ch=0;
//buffer for input as isread only accpet byte so we have to made buff byte
byte[] buff = new byte[1024];

//isread will return the buff's length
ch = is.read(buff);

String content = new String(buff,0,ch);
System.out.println(content);
//also os stream only accept array of bytes

os.write(String.valueOf(content.length()).getBytes());
//close I/O stream
is.close();
os.close();
socket.close();


}catch(Exception e){
System.out.println(e.toString());
}
}


}
# ,
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×