今天复习了一下网络底层的socket编程,socket编程的大致步骤如下:
1、创建服务器端SocketServer,并定义SocketServer的监听端口;
2、ServerSocket调用accept( )方法,是指处于阻塞;
3、创建客户端的Socket,并设置服务器的IP和端口;
4、客户端发送连接请求,建立连接;
5、分别取得服务器和客户端Socket的InputStream和OutputStream;
6;利用Socket和ServerSocket进行数据传输。
其中比较重要的只是点是文件的I/O操作,以及Socket的几个主要API:
1、getInputStream(); //返回Socket接收到的InputStream
2、getOutputStream(); //返回Socket向外传输(另一端为接收)的OutputStream
3、ServerSocket 的accept() //使服务器处于阻塞状态,直到客户端连接
/*
*服务器端代码
*
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server
{
public static void main(String[] args)
{
new Server();
}
public Server()
{
try
{
ServerSocket ss = new ServerSocket(8888);
while (true)
{
// 服务器接收消息
Socket s = ss.accept();
InputStreamReader isr = new InputStreamReader(s
.getInputStream());
BufferedReader in = new BufferedReader(isr);
String line = in.readLine();
System.out.println("Client发送的消息是: " + line);
// 把成功信息反馈回客户端
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
out.println("已经接受到消息了!");
out.close();
in.close();
isr.close();
s.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
/*
*
*客户端代码
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client
{
public static void main(String[] args)
{
new Client();
}
public Client()
{
try
{
System.out.println("正在连接Server中");
Socket socket = new Socket("localhost", 8888);
System.out.println("连接成功!");
System.out.println();
// 向服务器发消息
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
System.out.print("请输入信息:");
out.println(br.readLine());
// 接受服务器端消息
BufferedReader in = new BufferedReader(new InputStreamReader(socket
.getInputStream()));
System.out.println("Server回复的消息: " + in.readLine());
br.close();
out.close();
in.close();
socket.close();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}