- Java code
package SocketDemo;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 loginClient { public static void main(String[] args){ try {//建立客户端socket连接 ,指定服务器位置,急端口 Socket socket=new Socket("localhost",8888); //得到socket的读写流 OutputStream os=socket.getOutputStream(); PrintWriter pw=new PrintWriter(os); //输入流 InputStream is=socket.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); String info="用户名:tom;用户密码:123456"; pw.write(info); pw.flush(); socket.shutdownOutput();//关闭输出流 //接受服务器响应 String reply=null; while(!((reply=br.readLine())==null)){ System.out.println("我是客户端!!服务器端的响应是"+reply); } br.close(); is.close(); 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(); } }}
- Java code
package SocketDemo;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 LoginServer { public static void main(String [] args){ try { //建立服务器Socket对象,绑定端口开始监听,建议使用大于1024端口 ServerSocket ss=new ServerSocket(8888); //使用accpet方法阻塞等待监听,获得连接 Socket socket=ss.accept(); //获得输入流 InputStream is=socket.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); //获得输出流 OutputStream os=socket.getOutputStream(); PrintWriter pw=new PrintWriter(os); // 读取输入信息 String info=null; while(!((info=br.readLine())==null)){ System.out.println("我是服务器!!用户信息为"+info); } String reply="welcome"; pw.write(reply); pw.flush(); pw.close(); os.close(); br.close(); is.close(); socket.close(); ss.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
服务器端怎么报异常?? 谢谢
------解决方案--------------------
运行了客户端么?
public class loginClient {
public static void main(String[] args){
? try {//建立客户端socket连接 ,指定服务器位置,急端口
? System.out.println("尝试连接服务器8888");
? Socket socket=new Socket("localhost",8888);
? System.out.println("服务器连接成功");
? //得到socket的读写流
? OutputStream os=socket.getOutputStream();
? PrintWriter pw=new PrintWriter(os);