本文总结TCP、UDP和URL三种网络编程方法
一、TCP
package ;
import ;
import ;
import ;
import ;
import ;
public class TestTCPClient {
private static Socket socket;
private static OutputStream outputStream;
private static InputStream inputStream;
public static void main(String[] args) {
try {
("我是客户端...");
socket = new Socket("127.0.0.1",8866);
outputStream = ();
("我是客户端发送的数据".getBytes());
();//冲刷
inputStream = ();
byte[] b=new byte[1024];
(b);
(new String(b));
} catch (UnknownHostException e) {
();
} catch (IOException e) {
();
} finally{
try {
();
();
} catch (IOException e) {
();
}
}
}
}
package ;
import ;
import ;
import ;
import ;
import ;
public class TestTCPServer {
private static ServerSocket serverSocket;
private static InputStream inputStream;
private static Socket accept;
private static OutputStream outputStream;
public static void main(String[] args) {
try {
("我是服务器...");
serverSocket = new ServerSocket(8866);
accept = ();//等待 接收请求
inputStream = ();
byte[] b=new byte[1024];
(b);
(new String(b));
outputStream = ();
("我是服务器端发送的数据".getBytes());
();
} catch (IOException e) {
();
} finally{
try {
();
();
} catch (IOException e) {
();
}
}
}
}
二、UDP
package ;
import ;
import ;
import ;
import ;
import ;
import ;
public class TestUDPClient {
private static DatagramSocket datagramSocket;
private static DatagramPacket sdp;
private static DatagramPacket dp;
public static void main(String[] args) {
try {
datagramSocket = new DatagramSocket();
byte[] a="我是客户端发送的数据".getBytes();
sdp = new DatagramPacket(a, ,("127.0.0.1"),9778);
(sdp);
byte[] b=new byte[1024];
dp = new DatagramPacket(b, 1024);
(dp);//接收数据
(new String((),(),()));
} catch (SocketException e) {
();
} catch (UnknownHostException e) {
();
} catch (IOException e) {
();
}
}
}
package ;
import ;
import ;
import ;
import ;
import ;
public class TestUDPServer {
private static DatagramSocket datagramSocket;
private static DatagramPacket dp;
private static DatagramPacket sdp;
public static void main(String[] args) {
try {
datagramSocket = new DatagramSocket(9778);
byte[] b=new byte[1024];
dp = new DatagramPacket(b, 1024);//用于接收
(dp);//接收数据
InetAddress caddres=();
int port=();
("接收到的客户端信息:"+caddres+port+new String((),(),()));
byte[] a="服务器返回的数据".getBytes();
sdp = new DatagramPacket(a, ,caddres,port);
(sdp);
} catch (SocketException e) {
();
} catch (IOException e) {
();
} finally{
();
}
}
}
三、URL
package ;
import ;
import ;
import ;
import ;
import ;
public class TestURL {
private static URL url;
private static URLConnection urlConnection;
private static InputStream inputStream;
public static void main(String[] args) {
try {
url = new URL("/");
urlConnection = ();
(());//获取主机名
(());//获取端口
(());
byte[] b=new byte[1024];
inputStream = ();
(b);
(new String(b));
} catch (MalformedURLException e) {
();
} catch (IOException e) {
();
} finally{
try {
();
} catch (IOException e) {
();
}
}
}
}