Objective
When transmitting data over a network, the TCP/UDP is generally used for data transmission. But the two difference is that TCP is reliable and UDP is unreliable. The two common point is that you need to set up a socket socket to bind the IP address and port ports. However, the server and client socket is a bit different, the server side needs to display the specified port number for data monitoring, and the client only need to specify the IP on the line, the port number is allocated by the operating system.
Basic class
(1) InetAddress class
This class is to represent the IP address in the Internet, commonly used methods are:
- Getbyname (String Host) static method, given host name, to obtain an IP address object
- Gethostaddress () Gets the IP address of the host
(2) Inetsocketaddress class
This class is a socket related, he is used to create socket sockets, IP address and port binding, the main use is its constructor:
- Inetsocketaddress (inetaddress addr, int port)
- Inetsocketaddress (String hostname, int port)
Server-side sockets
This is only a brief description of TCP sockets, let us first look at how to write a simple server, here first with Linux C to achieve.
< Time . h > int main (int argc, char** argv) { int listenfd, CONNFD; Socketlen_t Len; struct sockaddr_in servaddr, cliaddr; Char Buff[maxline]; time_t ticks; LISTENFD = Socket (af_inet, sock_stream, 0); Bzero (&servaddr, (SA *)&servaddr, sizeof (SERVADDR)); Listen (LISTENFD, Listenq); for (;;) { len = sizeof (CLIADDR); CONNFD = Accept (LISTENFD, (SA *)&cliaddr&len); Write (CONNFD, Buff, strlen (buff)); Close (CONNFD);} }
Fundamentals of Java Network programming