TCP & UDP

1 TCP

1.1 ServerSocket

/**
 * author: huantaoliu
 * function: try to use tcp socket programming
 * time: 09.19.2012
 */
package com.socket;

import java.io.*;
import java.net.*;

public class TCPServer {
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		ServerSocket ss = new ServerSocket(6666);
		while(true){
			Socket s = ss.accept();
			System.out.println("connected one");
			DataInputStream dis =new DataInputStream(s.getInputStream());
			System.out.println(dis.readUTF());
			
		}
		
	}

}

socket is used to communicate between Server and Client. All the classes we need for the Server are in the package java.net.ServoerSocket. The example shows the main steps we need to start a connecton.

Step 1:

ServerSocket ss = new ServerSocket(6666);
/**
 * we regist the 6666 port for the socket ss at the server side
 */

Step 2:

Socket s = ss.accept();
/**
 *  if there is an request to connect to this port, accept it and get the client socket that want to connect to it.
 */

Step 3:

DataInputStream dis =new DataInputStream(s.getInputStream());
/**
 *  we get the stream, which is the inputstream of the client socket that is connected to this port, than we use dis.readUTF() to 
 *  print out the message that passed from the client server.
 */


1.2 Client socket

client sokcet can use the package java.net.Socket.  It has to first regist as a client socket and also include the port number of the server  that it want to connect to. Then if the ServerSocket accepted it, the connection is set up ,and the client can use outputStream to pass message.

/**
 * author: huantaoliu
 * function: try to use tcp socket programming
 * time: 09.19.2012
 */
package com.socket;
import java.net.*;
import java.io.*;

public class TCPClient {
	public static void main(String [] args)throws Exception{
		Socket s = new Socket("127.0.0.1",6666);
		OutputStream os = s.getOutputStream();
		DataOutputStream dos = new DataOutputStream(os);
		dos.writeUTF("hello server!");
		dos.flush();
		dos.close();
		s.close();
	}

}

Step 1:

Socket s = new Socket("127.0.0.1",6666);
/**
 * the client regist a socket, declare its own IP and the port number of the sever that it want to connect to.
 */

Step 2:

OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("hello server!");
/**
 * After setp 1, it waits for the reaction of server, if server accept it, it will use the outputStream to write message, and this
 * message can be catched at the server side and be printed out by using DataInputStream's read() method.
*/

1.3 InputStream and OutPutStream


as shown here, if the server wants to read the client's data, it has to use its InputStream as follows:

DataInputStream dis =new DataInputStream(s.getInputStream()); // s is the client socket's name

as the same way, if the server wants to send messages to the client, the server has to write it into its OutputStream, and the client may read it through inputStream(using server.getInputStream method)

2 UDP

2.1 UDP client

package tests;
import java.net.*;
import java.io.*;

public class TestUDPClient
{
	public static void main(String args[]) throws Exception
	{
			String value = "";
			DatagramSocket aSocket = null;
			try {   //step 1: create a client socket,whose port number is 8888
				aSocket = new DatagramSocket(8888);
                                //step 2: create a byte array which will be used to store message
                                byte [] m = "0001".getBytes();
                                //step 3: create a InetSocketAddress which will be binded in the packet to find the UDP server
                                InetSocketAddress aHost = new InetSocketAddress("127.0.0.1", 9999);
                                //step 4: create a datagram packet,which will be send by client socket.
                                //datagram packet includes bytearray and its length and the InetSocketAddress
                                DatagramPacket request = new DatagramPacket(m, "0001".length(), aHost);
				aSocket.send(request);
                                //create a datagrampacket initialize its byte array and length, which will be used by the client socket
                                // to receive data from UDP server
                                byte[] buffer = new byte[1000];
				DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
				aSocket.receive(reply);
                                //use this method to display the received data
                                value = new String(reply.getData());
				System.out.println("Reply: " + new String(reply.getData()));
			}
			catch (SocketException e){System.out.println("Socket: " + e.getMessage());}
			catch (IOException e){System.out.println("IO: " + e.getMessage());}
			finally {if(aSocket != null) aSocket.close();
			} 
			
		}
		
}

2.2 UDP server

import java.net.*;
import java.io.*;

public class UDPServer{
	public static void main(String args[]){
		DatagramSocket aSocket = null;
		try{
		    aSocket = new DatagramSocket(9999);
		    byte[] buffer = new byte[1000];
		while(true){
			DatagramPacket request = new DatagramPacket(buffer, buffer.length);
			aSocket.receive(request);
			DatagramPacket reply = new DatagramPacket(request.getData(),
			request.getLength(), request.getAddress(), request.getPort());
			aSocket.send(reply);
                        //*************************test the client's port*************************
                        System.out.println(new String(request.getData()).trim()+"  "+new String(request.getAddress().getHostAddress())
                        +"   "+request.getPort());
                }
		}catch (SocketException e){System.out.println("Socket: " + e.getMessage());
		}catch (IOException e) {System.out.println("IO: " + e.getMessage());}
		finally {if(aSocket != null) aSocket.close();}
	}
}

In the server, we first create a DatagramSocket of server, and define the port number to be 9999. Then create a DatagramPacket and give the buffer and its lenght to the DatagramPacket to receive the packet from the client. Then create a DatagramPacket to send info back to the client(aSocket.send(reply)).

request.getData() returns the buffer array used to store the data and the request.getLength() returns the lenght of the data which sotored in the buffer array.

request.getPort() returns the client socket's associated port:


If we define the port number of the client socket, everytime the client wants to send request to the server, it uses the same port, see the code of the client file:

aSocket = new DatagramSocket(4444);
in the server code, the request.getPort() will always be 4444:


But if we didn't give the port number when defining the client socket, everytime the client wants to send a request to the server, the system will give a random port to the client:

aSocket = new DatagramSocket();

The result will be:




3 JAVA Inet

package tests;
/**
*comes from the blog of csh624366188: http://blog.csdn.net/csh624366188
*
**/
import java.net.InetAddress;

public class Action {
	public static void main(String[] args) {
		try {
			// using domain name to create the InetAddress
			InetAddress inet1 = InetAddress.getByName("www.163.com");
			System.out.println(inet1);
			// using IP Address to create the InetAddress
			InetAddress inet2 = InetAddress.getByName("127.0.0.1");
			System.out.println(inet2);
			// using localhost to create InetAddress
			InetAddress inet3 = InetAddress.getLocalHost();
			System.out.println(inet3);
			// get the host name of the InetAddress
			String host = inet3.getHostName();
			System.out.println("域名:" + host);
			// get the IP of the InetAddress
			String ip = inet3.getHostAddress();
			System.out.println("IP:" + ip);
		} catch (Exception e) {
		}
	}
}

To create the InetAddress instance we have to use the "factory method", it is a static method called by the main() method to create the instance of the class. There are 3 factory method that we can use to create an instance of InetAddress as shown in the programm above, they are InetAddress.getByName(hostname), InetAddress.getByName(Ip address); InetAddress.getLocalHost();





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值