一、基于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();
}
}
}