一、基於TCP的socket實現
三次握手,有連接的,可靠地,數據大的
主要用到的類:Socket (客戶端和服務端都需要),ServerSocket(服務端用)
- Server端代碼示例:
public class Server {
static int port = 1000;
/**
* @param args
*/
public static void main(String[] args) {
/*
* 創建服務器端的對象ServerSocket
* 監聽Socket連接
* 通過返回的os流
*/
ServerSocket server = null;
try {
server = new ServerSocket(port);
Socket socket = server.accept(); //返回client方的socket對象
InputStream is = socket.getInputStream();
byte[] b = new byte[1024];
int len = 0;
while((len = is.read(b))!=-1){
String inputContent = new String(b,0,len);
System.out.println("received:"+inputContent);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
}
}
}
- Client端代碼示例:
public class Client {
static String ip = "192.xxx.xx.xxx";
static int port = 1000;
/**
* @param args
*/
public static void main(String[] args) {
/*
* 1. 創建一個客戶端的socket對象
* 2. 建立連接
* 3. 通過io流在管道內傳輸數據
* 4. 關閉socket
*/
Socket client =null;
try {
client = new Socket(ip,port);
OutputStream os = client.getOutputStream();
os.write("tcp".getBytes());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(client !=null){
try {
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
基於UDP的socket實現:
無連接,不可靠的:
基於UDP的Server端代碼:
public class ReceiveClass {
/**
* @param args
*/
public static void main(String[] args) {
// 1. 創建UDP協議對象 DatagramSocket ds = new ;
// 2. 打包64k內的數據 DatagrapPacket dp = new ;
// 3. 接收
DatagramSocket ds = null;
try {
ds = new DatagramSocket(9999);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);//阻塞方法
byte[] b = dp.getData();
System.out.println("received data="+new String(b,0,dp.getLength()).trim());
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
基於UDP的Client端代碼:
public class SendClass {
/**
* @param args
*/
public static void main(String[] args) {
try {
DatagramSocket ds = new DatagramSocket() ;
byte[] buf = "I am send data".getBytes();
InetAddress inetAddress = InetAddress.getByName("XXX.XXX.86.XXX");
DatagramPacket dp = new DatagramPacket(buf,0,buf.length,inetAddress, 9999);
ds.send(dp);
System.out.println("send data="+buf);
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}