您好,登錄后才能下訂單哦!
TCP:模擬登錄 :多個客戶端,先后等待
public class tcp {
public static void main(String[]args) throws IOException
{
System.out.println("服務器啟動中...");
ServerSocket server=new ServerSocket(8888);
boolean flag=true;
while(flag) {
Socket client=server.accept(); //一個客戶端建立連接
System.out.println("一個客戶端建立了連接");
new Thread(new channel(client)).start();
}
}
static class channel implements Runnable{
private Socket client;
private DataInputStream dis; //輸入流
DataOutputStream dos; //輸出流
public channel(Socket client)
{
this.client=client;
try {
dis=new DataInputStream(client.getInputStream());
dos=new DataOutputStream(client.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
release();
}
}
public void run()
{
String uname="";
String password="";
String data=receive();
String[] datas=data.split("&");
uname=datas[0];
password=datas[1];
if(uname.equals("杜雨龍")&&password.equals("你最帥"))
{
send("登陸成功");
}else
{
send("登錄失敗");
}
release();
}
//接收數據
private String receive()
{
String data="";
try {
data = dis.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
//發送數據
private void send(String msg)
{
try {
dos.writeUTF(msg);
dos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
//釋放資源
private void release()
{
try {
if(null!=dis)
{
dis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(null!=dis)
{
dos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(null!=client)
{
client.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
客戶端: 存儲文件
public class tcp2 {
public static void main(String[]args) throws IOException
{
System.out.println("客戶端啟動中...");
Socket client=new Socket("localhost",8888);
//發送
new send(client).sendto();
new receive(client).receiveto();
client.close();
}
static class send{
private Socket client;
private DataOutputStream dos;
private BufferedReader br;
private String msg;
public send(Socket client)
{
this.client=client;
br=new BufferedReader(new InputStreamReader(System.in));
msg=init();
try {
dos =new DataOutputStream(client.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendto()
{
try {
dos.writeUTF(msg);
dos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public String init()
{
try {
System.out.println("請輸入用戶名");
String name=br.readLine();
System.out.println("請輸入密碼");
String password=br.readLine();
return name+"&"+password;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
static class receive{
private DataInputStream dis;
private Socket client;
public receive(Socket client)
{
this.client=client;
DataInputStream dis=new DataInputStream(client.getInputStream());
}
public void receiveto()
{
String data;
try {
data = dis.readUTF();
System.out.println(data);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。