一.Socket的基础知识
1.socket的位置作用与典型的TCP/IP模型结构
2.socket的分类(原始式套接字、流式套接字、数据报式套接字)
二、TCP编程示例
package com.socket;
import java.io.Serializable;
/** * 序列化对象实体类 * @author xue * */
public class Person implements Serializable {
private String account;
private String pwd;
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
package com.socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
/** * 多线程实现服务器与多客户端之间的通信 */
public class ThreadSocket extends Thread {
protected Socket socket=null;
public ThreadSocket(Socket socket){
this.socket=socket;
}
public void run() {
try {
/* * 读取信息 */
InputStream is=socket.getInputStream();//获取输入流
ObjectInputStream obj=new ObjectInputStream(is);//对象流输入
try {
Person p=(Person) obj.readObject();
//用户信息
System.out.println("用户账号:"+p.getAccount()+"----------"+"用户密码:"+p.getPwd());
InetAddress address=socket.getInetAddress();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
socket.shutdownInput();//关闭输入流
/* * 给客户端返回信息 */
OutputStream os=socket.getOutputStream();
PrintWriter pw=new PrintWriter(os);
pw.write("欢迎用户的到来.....");
pw.flush();
socket.shutdownOutput();
is.close();
pw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.socket;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/* * socket服务器 */
public class Server {
public static void main(String[] args) {
getConn();
}
public static void getConn(){
try {
ServerSocket serverSocket=new ServerSocket(10086);//创建一个socket
Socket socket=null;
/* * 起用多线程监听 */
int i=0;//用于统计有几个用户访问该服务器
while(true){
//循环调用accept()等待客户端连接
socket=serverSocket.accept();
ThreadSocket threadSocket=new ThreadSocket(socket);
threadSocket.start();
i++;
System.out.println("一共有:"+i+"个人访问该服务器");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
/* * socket客户端 */
public class Client {
public static void main(String[] args) {
getConn();
}
public static void getConn(){
try {
Socket socket=new Socket("127.0.0.1",10086);
/* * 发信息至服务器 */
OutputStream os=socket.getOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(os);
Person p=new Person();
p.setAccount("123445");
p.setPwd("abcd");
oos.writeObject(p);
/* * 返回信息给服务端 */
InputStream is=socket.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
String replyInfo=null;
while((replyInfo=br.readLine())!=null){
System.out.println("客户端读取服务端发来的消息:"+replyInfo);
}
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.socket;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/** * UDP网络编程 */
public class UDPServer {
public static void main(String[] args) {
getUDPClientConn();
}
/* * 与客户端进行通信 */
public static void getUDPClientConn(){
try {
//====================获取客户端发来的信息 =====================//
//创建服务器端DatagramSocket,指定端口
DatagramSocket socket=new DatagramSocket(10086);
byte [] datagram=new byte[1024];
//创建数据报,用于接受客户端发送的数据
DatagramPacket packetFromClient=new DatagramPacket(datagram, datagram.length);
//接收客户端发送的数据,此方法之前会发生阻塞
socket.receive(packetFromClient);
//获取数据
String info=new String(datagram, 0, datagram.length);
System.out.println("客户端发来了信息:"+info);
//===================向客户端响应发送信息====================//
InetAddress address=packetFromClient.getAddress();//客户端地址
int port=packetFromClient.getPort();
byte[] sendInfo="服务端返回信息:欢迎你".getBytes();//返回信息
DatagramPacket packetToClient=new DatagramPacket(sendInfo, 0, sendInfo.length, address, port);
socket.send(packetToClient);
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.socket;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/** * UDP网络编程客户端 */
public class UDPClient {
public static void main(String[] args) {
getUDPServerConn();
}
public static void getUDPServerConn(){
//================客户端发送信息至服务器====================//
try {
InetAddress address=InetAddress.getByName("127.0.0.1");//服务器地址
int port=10086;
byte[] dataToServer="客户端请求连接服务端".getBytes();
DatagramPacket sendToServerPacket=new DatagramPacket(dataToServer, dataToServer.length, address, port);
DatagramSocket socket=new DatagramSocket();
socket.send(sendToServerPacket);
//=================获取服务端发过来的信息==================//
byte[]dataFromServer=new byte[1024];
DatagramPacket dataFromServerPacket=new DatagramPacket(dataFromServer, 0, dataFromServer.length);
socket.receive(dataFromServerPacket);
String info=new String(dataFromServer,0,dataFromServer.length);
System.out.println("服务端发来的信息:"+info);
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
四、其他内容
1. InetAddress类用于标识网络上的硬件资源,标识互联网协议(IP)地址。
2. URL(Uniform Resource Locator)统一资源定位符,表示Internet上某一资源的地址,协议名:资源名称
3. 示例:
package com.socket;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
/** * 1.InetAddress类用于标识网络上的硬件资源,标识互联网协议(IP)地址。 * 2.通过URL对象的openStream()方法可以得到指定资源的输入流,通过流能够读取或访问网页上的资源 */
public class SocketServer {
public static void main(String[] args) {
getLocalHost();
getWebDateByUrl();
}
public static void getLocalHost(){
try {
//本地主机信息
InetAddress address=InetAddress.getLocalHost();
System.out.println("本地IP地址:"+address.getHostAddress());//Ip地址
System.out.println("本地主机名:"+address.getHostName());//计算机名
//其他主机信息
InetAddress otherAddress=InetAddress.getByName("172.18.233.1");
System.out.println(otherAddress.getHostName());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/* * 通过URL读取网页内容 */
public static void getWebDateByUrl(){
try {
URL url=new URL("http://www.baidu.com");
InputStream is=url.openStream();//通过openStream获取输入流
InputStreamReader isr=new InputStreamReader(is, "UTF-8");//输入流转为字符流
BufferedReader br=new BufferedReader(isr);//加入缓冲区
String data=br.readLine();
String html="";
FileOutputStream fos=new FileOutputStream(new File("D://baidu.html"));//写到网页文件
while(data!=null){
System.out.println(data);
html+=data;
data=br.readLine();
}
fos.write(html.getBytes("UTF-8"));
is.close();
isr.close();
br.close();
fos.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}