请问Socket编程的基本步骤是怎样的?最好能写一个简单的程序Java演示一下,主要是接受数据。谢谢!
1个回答
2014-10-13
展开全部
SERVER端:
--------------------------------------------------------
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server extends Thread {
private Socket clientSocket;
public Server(Socket clientSocket) {
this.clientSocket = clientSocket;
}
public void run() {
DataInputStream dis = null;
DataOutputStream dos = null;
try {
dis = new DataInputStream(clientSocket.getInputStream());
dos = new DataOutputStream(clientSocket.getOutputStream());
while (true) {
String temp = dis.readUTF();
if ("over".equals(temp)) {
break;
}
dos.writeUTF("from server:" + temp);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (dis != null) {
dis.close();
}
if (dis != null) {
dos.close();
}
if (clientSocket != null) {
clientSocket.close();
}
} catch (IOException e) {
}
}
}
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(8008);
while (true) {
Socket clientSocket = ss.accept();
// 针对每个客户端, 启一个Server线程专门处理此客户端的请求。
Server server = new Server(clientSocket);
server.start();
}
}
}
CLIENT端:
----------------------------------------
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws Exception {
// 输入流1, 从键盘进入Client。
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
Socket clientSocket = new Socket("127.0.0.1", 8008);
// 输入流2, 从服务器端进入Client的流对象。
DataInputStream dis = new DataInputStream(clientSocket.getInputStream());
// 输出流, 从Client出去, 到服务器端。
DataOutputStream dos = new DataOutputStream(clientSocket.getOutputStream());
while (true) {
// 从键盘输入读取
String msg = br.readLine();
// 将读取信息发送给服务器端
dos.writeUTF(msg);
//输入QUIT退出
if ("QUIT".equals(msg)) {
break;
}
//读取从服务器返回的信息
String temp = dis.readUTF();
System.out.println(temp);
}
br.close();
dis.close();
dos.close();
clientSocket.close();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询