一:实现TCP网络编程
客户端发送信息给服务端
代码示例:
public class TCPTest {
@Test
public void client() {
Socket socket = null;
OutputStream os = null;
try {
//创建socket对象指明服务器端的IP和端口好
InetAddress inet = InetAddress.getByName("127.0.0.1");
socket = new Socket(inet, 6677);
//获取输出流来输出数据
os = socket.getOutputStream();
//写出数据
os.write("你好我是客户端".getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
//资源关闭
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
*@ClassName TCPTest
*@Description 服务器端接受客户端数据
*@Param []
*@Return void
*@Date 2020/2/10 15:11
*@Author Roy
*/
@Test
public void server(){
ServerSocket ss= null;
Socket s= null;
InputStream is= null;
ByteArrayOutputStream baos= null;
try {
//创建服务器端的socket指定自己的端口号
ss = new ServerSocket(6677);
//调用accept接受来自客户端的socket
s = ss.accept();
//获取输入流
is = s.getInputStream();
//读取输入流中数据
baos = new ByteArrayOutputStream();
byte[] bytes=new byte[10];
int size;
while((size=is.read(bytes))!=-1){
baos.write(bytes,0,size);
}
//输出
System.out.println(baos.toString());
System.out.println("收到了来自于"+s.getInetAddress().getHostAddress()+"信息");
} catch (IOException e) {
e.printStackTrace();
} finally {
//资源关闭
if(baos!=null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is!=null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(s!=null) {
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(ss!=null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
二:UDP网络编程
代码示例:
public class UDPTest {
@Test
public void sender(){
DatagramSocket socket= null;
try {
socket = new DatagramSocket();
String string="UDP测试发送";
byte[] bytes=string.getBytes();
InetAddress inet=InetAddress.getLocalHost();
DatagramPacket packet=new DatagramPacket(bytes,bytes.length,inet,9090);
//发送包
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭资源
if(socket!=null)
socket.close();
}
}
@Test
public void receiver(){
DatagramSocket socket= null;
try {
socket = new DatagramSocket(9090);
byte[] buffer=new byte[100];
DatagramPacket packet=new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);
System.out.println(new String(packet.getData(),0,packet.getLength()));
} catch (IOException e) {
e.printStackTrace();
} finally {
if(socket!=null)
socket.close();
}
}
}