Java—网络编程
网络通信协议
客户端发送信息给服务器
举个例子:实现简单的登录功能
User类
package Socket;
import java.io.Serializable;
public class User implements Serializable {
private String userName; //用户名
private String pwd; //密码
public User() {
}
public User(String userName, String pwd) {
this.userName = userName;
this.pwd = pwd;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
服务器类
package Socket;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class LoginServer {
public static void main(String[] args) {
try {
//1.创建一个服务器Socket
ServerSocket serverSocket=new ServerSocket(5000);
//2.使用accept()等待客户的通信
Socket socket=serverSocket.accept();
//3.获得输入流,获得相应的用户请求
InputStream is=socket.getInputStream();
ObjectInputStream ois=new ObjectInputStream(is);
User user=(User)ois.readObject();
System.out.println("我是服务器,接收到的信息:"+user.getUserName()+"---"+user.getPwd());
//给客户端一个响应
String reply="欢迎登录!";
byte[] replys=reply.getBytes();
OutputStream os=socket.getOutputStream();
os.write(replys);
//4.释放相应资源
os.close();
ois.close();
is.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
客户端类
package Socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class LoginClient {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
//1、创建一个客户端Socket
Socket socket=new Socket("localhost",5000);
//2、通过输出流发送请求
OutputStream os=socket.getOutputStream();
System.out.println("请输入姓名");
String name = sc.next();
System.out.println("请输入密码");
String passwd = sc.next();
User user=new User(name,passwd);
ObjectOutputStream oos=new ObjectOutputStream(os);
oos.writeObject(user);
socket.shutdownOutput();
//通过输入流来接收到服务器给客户端的响应
InputStream is=socket.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
String reply;
while((reply=br.readLine())!=null){
System.out.println("服务器的响应:"+reply);
}
//3、释放资源
br.close();
is.close();
os.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
提示:先执行服务器再执行客户端,要不然不报错
客户端输出结果
服务器端输出结果