要求: 创建一个客户端, 向服务器发送数据
private Socket socket;
public Client(){
try {
socket = new Socket("localhost",8088);
} catch (Exception e) {
e.printStackTrace();
}
}
/**客户端开始工作的方法
public void start(){
try {
/*
* 通过Socket对象获取输出流,
* 将数据发送给服务器
*/
OutputStream os = socket.getOutputStream();
PrintWriter pw =
new PrintWriter(
new OutputStreamWriter(os));
Scanner scan = new Scanner(System.in);
while(true){
String input = scan.next();
pw.println(input);
pw.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Client client = new Client();
client.start();
}
2.Server2
1.Client2:
public class Client {
/*属性:Socket,指定服务器的IP和端口*/private Socket socket;
public Client(){
try {
socket = new Socket("localhost",8088);
} catch (Exception e) {
e.printStackTrace();
}
}
/**客户端开始工作的方法
public void start(){
try {
/*
* 通过Socket对象获取输出流,
* 将数据发送给服务器
*/
OutputStream os = socket.getOutputStream();
PrintWriter pw =
new PrintWriter(
new OutputStreamWriter(os));
Scanner scan = new Scanner(System.in);
while(true){
String input = scan.next();
pw.println(input);
pw.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Client client = new Client();
client.start();
}
}