socket编程 客户端与服务端通信

时间:2021-09-12 22:11:27

传输对象的网络编程:

 客户端代码:

package SocketDemo;

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;

/**
* 客户端类
* @author Administrator
*
*/
public class ClientLogin {
public static void main(String[] args) {
//1.创建一个socket对象(指定服务器IP,端口号)
try {
Socket socket = new Socket("localhost",8000);
//2.打开输出 流,发送请求
OutputStream os = socket.getOutputStream();
InputStream is = socket.getInputStream();
User user = new User(); //创建用来发送的对象
user.setName("TOM");
user.setPwd("1234");
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(user);
socket.shutdownOutput();
//服务器接收客户端反馈
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String info = "";
while((info=br.readLine())!=null){
System.out.println("我是客户端,服务器的响应是:"+info);
}
os.close();
is.close();
oos.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

//3.关闭资源

}
}

 

————---------------------------------------------------------------------------------------------

服务器端代码:

package SocketDemo;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
* 服务器类
* @author Administrator
*
*/
public class ServerLogin {
public static void main(String[] args) {
//1.创建一个ServerSocket对象 指定端口号
try {
ServerSocket serversocket = new ServerSocket(8000);
//2.监听客户端请求
Socket socket = serversocket.accept();
//3.打开输入流,处理用户请求
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
ObjectInputStream ois = new ObjectInputStream(is);
User user;
try {
user = (User)ois.readObject();
System.out.println("我是服务器,客户端信息为:用户名:" + user.getName()+ ",密码:" + user.getPwd());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
socket.shutdownInput();
//服务器给客户端一个响应
//1.打开输出流,发送数据
String info = "欢迎您,登录成功!";
os.write(info.getBytes());
//4.关闭资源
is.close();
os.close();
ois.close();
socket.close();
serversocket.close();

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}



}
}

------------------------------------------------------------------------------

所传输的对象的类:

package SocketDemo;

import java.io.Serializable;

/**
* 用户类
* @author Administrator
*
*/
public class User implements Serializable{//实现Serializable接口是使该类对象可序列化,即可以通过流传输
private String name;
private String pwd;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}