以下是代码
服务器:
package com.zhang;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class InetAddress1 {
public static void main(String[] args){
try {
ServerSocket serverSocket=new ServerSocket(8888);
System.out.println("****服务器即将启动****");
Socket sc=serverSocket.accept();
InputStream is=sc.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
String in="";
while((in=br.readLine())!=null){
System.out.println("服务器:客户端发来的信息是"+in);
}
System.out.println("111");
sc.shutdownInput();
OutputStream os=sc.getOutputStream();
PrintWriter pw=new PrintWriter(os);
pw.write("欢迎光临!");
pw.flush();
os.close();
pw.close();
is.close();
isr.close();
br.close();
sc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端:
package com.zhang;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class client {
/**
* @param args
*/
public static void main(String[] args) {
try {
Socket socket=new Socket("localhost",8888);
OutputStream os=socket.getOutputStream();
PrintWriter pw=new PrintWriter(os);
pw.write("账户:zxcv200cool 密码:zxcvbnm2008");
pw.flush();
System.out.println("数据发送成功");
InputStream is1=socket.getInputStream();
InputStreamReader isr1=new InputStreamReader(is1);
BufferedReader br1=new BufferedReader(isr1);
String next=null;
while((next=br1.readLine())!=null){
System.out.println("客户端:服务器发来的信息是"+next);
}
is1.close();
isr1.close();
br1.close();
socket.close();
os.close();
pw.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}