愚人世界
2016-06-22 10:39
//服务器端的程序
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try {
ServerSocket server =new ServerSocket(9887);
while(true)
{
Socket socket =server.accept();
InputStream it =socket.getInputStream();
InputStreamReader its=new InputStreamReader(it);
BufferedReader br=new BufferedReader(its);
System.out.println("我是服务器 ,等待客户端输入数据");
String info =null;
while((info=br.readLine())!=null)
{
System.out.println(info);
info=br.readLine();
}
socket.shutdownInput();
br.close();
its.close();
it.close();
socket.close();
server.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//客户端的程序
import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) {
try {
Socket socket =new Socket("localhost",9887);
OutputStream os =socket.getOutputStream();
PrintWriter pw=new PrintWriter(os);
pw.write("用户名");
pw.flush();
socket.shutdownOutput();
pw.close();
os.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
将客户端的 pw.write("用户名");
改为 pw.println("用户名"); 就可以了,不知道为什么,求小伙伴一起讨论
Java Socket应用---通信是这样练成的
125012 学习 · 590 问题
相似问题