一、ServerSocket
java.lang.Object
|-java.net.ServerSocket
有子类SSLServerSocket。
此类实现服务器套接字。服务器套接字等待请求通过网络传入。它基于该请求执行某些操作,然后可能向请求者返回结果。 |
常用构造方法:
ServerSocket(int port) 创建绑定到特定端口的服务器套接字。 |
常用方法:
|
|
|
|
|
|
|
|
|
|
二、Socket
Java.lang.Object
|-java.net.Socket
常用构造方法:
Socket(InetAddress address, int port) |
|
常用方法:
void |
bind(SocketAddress bindpoint) |
void |
close() |
void |
connect(SocketAddress endpoint) |
void |
connect(SocketAddress endpoint, int timeout) |
getInetAddress() |
|
getInputStream() |
|
getOutputStream() |
|
int |
getPort() |
void |
shutdownInput() |
void |
shutdownOutput() |
三、DatagramSocket
Java.lang.Object
|-java.net.DatagramSocket
常用构造方法:
DatagramSocket(int port) |
|
DatagramSocket(int port, InetAddress laddr) |
常用方法:
应当注意的是,该类既能发送数据包也能接受数据包
void |
bind(SocketAddress addr) |
void |
close() |
void |
connect(InetAddress address, int port) |
void |
connect(SocketAddress addr) |
getInetAddress() |
|
void |
receive(DatagramPacket p) |
void |
send(DatagramPacket p) |
四、DatagramPacket
Java.lang.Object
|-java.net.DatagramPacket
常用构造方法:
构造方法摘要 |
|
DatagramPacket(byte[] buf, int length) |
|
DatagramPacket(byte[] buf, int length, InetAddress address, int port) |
|
DatagramPacket(byte[] buf, int length, SocketAddress address) |
常用方法:
getAddress() |
|
int |
getPort() |
void |
setAddress(InetAddress iaddr) |
void |
setData(byte[] buf, |
void |
setPort(int iport) |
void |
setSocketAddress(SocketAddress address) |
五、简单TCP应用实例1:服务端小写转大写服务
服务端程序:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket; /**
* 这是服务端程序
* @author kuangdaoyizhimei
*
*/
public class Server
{
public static void main(String args[]) throws IOException
{
ServerSocket ss=new ServerSocket(7894);
Socket s=ss.accept();
System.out.println(s.getInetAddress().getHostAddress()+"已连接。");
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
String str=null;
while((str=br.readLine())!=null)
{
System.out.println(str);
pw.println(str.toUpperCase());//注意println方法的使用在这里是必须的,否则会产生死锁
}
s.close();
ss.close();
}
}
客户端程序:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException; /**
* 这是客户端程序。
* @author kuangdaoyizhimei
*
*/
public class Client
{
public static void main(String args[]) throws UnknownHostException, IOException
{
Socket s=new Socket("192.168.1.101",7894);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
BufferedReader bin=new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
String str=null;
while((str=br.readLine())!=null)
{
pw.println(str);
String result=bin.readLine();
System.out.println(result);//注意println方法的使用在这里是必须的,否则会产生死锁
}
s.close();
}
}
运行结果:
服务端运行结果:
客户端运行结果:
二、简单UDP服务演示:局域网群聊小程序。
程序使用的广播地址是192.168.1.255,每个客户端的接收端口是6544。
程序中使用了多线程技术。
package p01.UDPTransferDemo.p01.UDPTransferDemo;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* 接收线程ReceiveThread
* @author kuangdaoyizhimei
*/
class ReceiveThread implements Runnable
{
DatagramSocket ds=null;
public ReceiveThread(DatagramSocket ds)
{
this.ds=ds;
}
@Override
public void run()
{
while(true)
{
try
{
byte buf[]=new byte[1024];
//2.创建接收数据报
DatagramPacket dp=new DatagramPacket(buf, buf.length);
ds.receive(dp);
//3.显示数据报信息
System.out.println(dp.getAddress().getHostAddress()+":"+dp.getPort()+":"+new String(dp.getData(),0,dp.getLength()));
}
catch(IOException e)
{
System.out.println("接受线程产生异常!");
}
}
}
}
/**
* 发送线程SendThread
* @author kuangdaoyizhimei
*
*/
class SendThread implements Runnable
{
DatagramSocket ds=null;
public SendThread(DatagramSocket ds)
{
this.ds=ds;
}
@Override
public void run()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str=null;
try {
while((str=br.readLine())!=null)
{
try
{
//2.创建发送数据包。
DatagramPacket dp=new DatagramPacket(str.getBytes(),str.getBytes().length,InetAddress.getByName("192.168.1.255"),6544);
//3.发送数据包
ds.send(dp);
}
catch(IOException e)
{
System.out.println("发送线程产生异常!");
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 主类UDPTransferDemo
* @author kuangdaoyizhimei
*
*/
public class UDPTransferDemo {
public static void main(String args[]) throws IOException
{
DatagramSocket Send=new DatagramSocket();
DatagramSocket Receive=new DatagramSocket(6544);
new Thread(new ReceiveThread(Receive)).start();
new Thread(new SendThread(Send)).start();
}
}
运行结果:
三、TCP应用之文本文件上传
在和源文件同一个文件夹中预先准备一个文本文件aim.txt,里面内容自定义。
服务端程序:
package p04.TCPUpperLoadFileDemo.p01.TCPUpperLoadTextFileDemo; import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket; public class TCPUpperLoadServer {
public static void main(String args[]) throws IOException
{
ServerSocket ss=new ServerSocket(9876);
Socket s=ss.accept();
InputStream is=s.getInputStream();
BufferedReader brIn=new BufferedReader(new InputStreamReader(is));
OutputStream os=s.getOutputStream();
BufferedWriter bwOut=new BufferedWriter(new OutputStreamWriter(os));
String str=null;
File file=new File("副本.txt");
BufferedWriter bw=new BufferedWriter(new FileWriter(file));
while((str=brIn.readLine())!=null)
{
System.out.println(str);
bw.write(str);
bw.newLine();//此处换行是为了写到文件的换行
bw.flush();
}
bw.close();
bwOut.write("上传成功!");
bwOut.flush();
s.close();
}
}
客户端程序:
package p04.TCPUpperLoadFileDemo.p01.TCPUpperLoadTextFileDemo; import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException; public class TCPUpperLoadClient { public static void main(String[] args) throws UnknownHostException, IOException
{
Socket socket=new Socket("192.168.209.1",9876);
InputStream is=socket.getInputStream();
BufferedReader brIn=new BufferedReader(new InputStreamReader(is));
OutputStream os=socket.getOutputStream();
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
File file=new File("aim.txt");
FileReader fr=new FileReader(file);
BufferedReader br=new BufferedReader(fr);
String str=null;
while((str=br.readLine())!=null)
{
bw.write(str);
bw.newLine();//此处换行是为了给服务器端读取一行的结束标记。
bw.flush();
}
socket.shutdownOutput();//没有这一句话两端将都处于等待状态。
br.close();
str=brIn.readLine();
System.out.println(str);
}
}
运行结果:
四、TCP应用之媒体文件上传。
准备:aim.mp4文件,放在和源代码文件同一个目录下
客户端:
package p04.TCPUpperLoadFileDemo.p02.TCPUpperLoadMultipleFileDemo; import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException; public class TCPUpperLoadMultipleFileClient { public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket=new Socket("192.168.209.1",9876);
InputStream is=socket.getInputStream();
OutputStream os=socket.getOutputStream();
byte buf[]=new byte[1024];
File file=new File("aim.mp4");
FileInputStream fis=new FileInputStream(file);
int length=0;
while((length=fis.read(buf))!=-1)
{
os.write(buf, 0, length);
os.flush();
}
fis.close();
socket.shutdownOutput(); /**
* 显示上传状态信息
*/
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String str=br.readLine();
System.out.println(str);
socket.close();
} }
服务端:
package p04.TCPUpperLoadFileDemo.p02.TCPUpperLoadMultipleFileDemo; import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket; public class TCPUpperLoadMultipleFileServer { public static void main(String[] args) throws IOException {
ServerSocket ss=new ServerSocket(9876);
Socket socket=ss.accept();
InputStream is=socket.getInputStream();
OutputStream os=socket.getOutputStream();
FileOutputStream fos=new FileOutputStream(new File("副本.mp4"));
byte buf[]=new byte[1024];
int length=-1;
while((length=is.read(buf))!=-1)
{
fos.write(buf, 0, length);
fos.flush();
}
fos.close();
os.write("文件上传成功!".getBytes());
socket.close();
ss.close();//服务器一般不关闭,这里只是用于演示,所以关闭。
}
}
运行结果:
五、TCP应用之QQ群聊。
客户端之输入端:
/**
* 此程序模拟QQ输入
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException; public class TCPTransferQQImitateClient { public static void main(String[] args) throws UnknownHostException, IOException {
System.out.println("这是用户信息输入窗口:");
Socket socket=new Socket("192.168.209.1",8080);
OutputStream os=socket.getOutputStream();
PrintWriter pw=new PrintWriter(os,true);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str=null;
while((str=br.readLine())!=null)
{
if(str.equals("over"))
{
break;
}
pw.println(str);
}
br.close();
pw.close();
socket.shutdownOutput();
socket.close();
}
}
客户端之接收端:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 此程序模拟群聊输出
* @author kuangdaoyizhimei
*
*/
public class ReceiveInformationClient { public static void main(String[] args) throws IOException {
System.out.println("这是群聊显示窗口:");
ServerSocket ss=new ServerSocket(8000);
while(true)
{
Socket s=ss.accept();
InputStream is=s.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String str=null;
str=br.readLine();
System.out.println(str);
}
}
}
服务端之用户接入端:
/**
* 此程序模拟服务器处理用户接入
*/
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.HashSet; public class TransmitServer {
public static void main(String[] args) throws IOException {
System.out.println("这是服务器处理多线程窗口:");
ServerSocket ss=new ServerSocket(8080);
HashSet<String>hs=new HashSet<String>();
while(true)
{
Socket socket=ss.accept();
System.out.println("用户"+socket.getInetAddress().getHostName()+"接入!");
Thread thread=new Thread(new ClientHandle(socket,hs));
thread.start();
}
}
}
服务端之转发端:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashSet;
/**
* 此程序模拟服务器处理单个用户的线程接入和数据转发。
* @author kuangdaoyizhimei
*
*/
public class ClientHandle implements Runnable {
private Socket socket;
private HashSet<String>list;
public ClientHandle(Socket socket, HashSet<String> list) {
this.socket=socket;
this.list=list;
} @Override
public void run() {
System.out.println("这是服务器处理单线程窗口:(核心窗口)");
try
{
list.add(socket.getInetAddress().getHostAddress());
InputStream is=socket.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String ip=socket.getInetAddress().getHostAddress();
int port=socket.getPort();
String str=ip+":"+port+" :";
String temp=null;
while((temp=br.readLine())!=null)
{
for(String s:list)
{
Socket sk=new Socket(s,8000);
OutputStream osm=sk.getOutputStream();
PrintWriter pw=new PrintWriter(osm,true);
pw.println(str+temp);
sk.close();
}
}
}
catch(IOException e)
{
System.out.println("用户"+socket.getInetAddress().getHostAddress()+"退出!");
}
}
}
运行结果: