服务端
package com.dyn.itheima.test7;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
// 创建服务器套接字
ServerSocket serverSocket = null;
// 创建套接字
Socket socket = null;
// 创建输入流对象
BufferedReader reader = null;
try {
serverSocket = new ServerSocket(10086);
// 获取客户端套接字
socket = serverSocket.accept();
// 获取客户端传来的数据
reader = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String data = reader.readLine();
System.out.println("接收到数据 " + data);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (!socket.isClosed()) {
try {
socket.close();
} catch (IOException e) { // TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
客户端
package com.dyn.itheima.test7;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args){
// 创建网络套接字
Socket socket = null;
// 创建输入流对象
BufferedReader reader = null;
// 创建输出流对象
BufferedWriter writer = null;
try {
socket = new Socket(InetAddress.getByName("127.0.0.1"), 10086);
// 键盘录入数据
reader = new BufferedReader(new InputStreamReader(System.in));
String data = reader.readLine();
//往服务器写数据
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.write(data);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
望大神不吝赐教!
|
|