Socket是网络上运行的两个程序间双向通讯的一端,它既可以接受请求,也可以发送请求,利用它可以较为方便的编写网络上的数据的传递。在java中,有专门的socket类来处理用户的请求和响应。利用SOCKET类的方法,就可以实现两台计算机之间的通讯。这里就介绍一下在JAVA中如何利用socket进行网络编程。
在Java中Socket可以理解为客户端或者服务器端的一个特殊的对象,这个对象有两个关键的方法,一个是getInputStream方法,另一个是getOutputStream方法。getInputStream方法可以得到一个输入流,客户端的Socket对象上的getInputStream方法得到的输入流其实就是从服务器端发回的数据流。GetOutputStream方法得到一个输出流,客户端Socket对象上的getOutputStream方法返回的输出流就是将要发送到服务器端的数据流,(其实是一个缓冲区,暂时存储将要发送过去的数据)。
程序可以对这些数据流根据需要进行进一步的封装。本文的例子就对这些数据流进行了一定的封装(关于封装可以参考Java中流的实现部分)。
服务端
SocketManager.javaSocketManagerSocketManagerSocketManagerSocketManager
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketManager {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) {
SocketManager manager = new SocketManager();
manager.doListen();
}
public void doListen() {
ServerSocket server;
try {
server = new ServerSocket(9991);
while (true) {
Socket client = server.accept();
new Thread(new SSocket(client)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//服务器进程
class SSocket implements Runnable {
Socket client;
public SSocket(Socket client) {
this.client = client;
}
public void run() {
DataInputStream input;
DataOutputStream output;
try {
input = new DataInputStream(client.getInputStream());
output = new DataOutputStream(client.getOutputStream());
//
String listMsg = input.readUTF();
output.writeUTF("Send : " + listMsg + " \r\n HelloVillage...");
System.out.println("Recive: " + listMsg);
listMsg = input.readUTF();
output.writeUTF("Send Second: " + listMsg + " \r\n HelloVillage...");
System.out.println("Recive Second: " + listMsg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
客服端
SocketClient.java
//点击(此处)折叠或打开 服务器
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketClient {
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("127.0.0.1", 9991);
//向服务器端第一次发送字符串
OutputStream netOut = socket.getOutputStream();
DataOutputStream doc = new DataOutputStream(netOut);
DataInputStream in = new DataInputStream(socket.getInputStream());
//向服务器端第二次发送字符串
doc.writeUTF("list");
String res = in.readUTF();
System.out.println(res);
doc.writeUTF("bye");
res = in.readUTF();
System.out.println(res);
doc.close();
in.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
}
}
}