我想实现服务器和客户端都可以收发信息,不知道哪里错了
package com.jwy.bb; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.UnknownHostException; public class SocketClient { public static void main(String[] args) { SocketClient client=new SocketClient(); client.start(); } public void start(){ Socket socket=null; BufferedWriter writer=null; BufferedReader reader=null; BufferedReader inputReader=null; try { socket=new Socket("127.0.0.1",9898); writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); reader=new BufferedReader(new InputStreamReader(socket.getInputStream())); inputReader=new BufferedReader(new InputStreamReader(System.in)); String inputContent; String receiveMsg; while((inputContent=inputReader.readLine())!=null){ writer.write(inputContent+"\n"); writer.flush(); } while((receiveMsg=reader.readLine())!=null){ System.out.println(receiveMsg); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ try { inputReader.close(); reader.close(); writer.close(); socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package com.jwy.aa;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import com.sun.imageio.spi.OutputStreamImageOutputStreamSpi;
public class SocketServer2 {
public static void main(String[] args) {
SocketServer2 socketserver2=new SocketServer2();
socketserver2.start();
}
public void start(){
ServerSocket socketserver=null;
Socket socket=null;
BufferedReader reader=null;
BufferedWriter writer=null;
BufferedReader inputContent=null;
try {
socketserver=new ServerSocket(9898);
System.out.println("server...");
socket=socketserver.accept();
System.out.println("server"+socket.hashCode()+"connection");
inputContent=new BufferedReader(new InputStreamReader(System.in));
reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
// writer=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String receiveMsg;
String inputcontent;
while((inputcontent=inputContent.readLine())!=null){
writer.write(inputcontent+"\n");
writer.flush();
}
while((receiveMsg=reader.readLine())!=null)
{
System.out.println(receiveMsg);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
reader.close();
socket.close();
writer.close();
inputContent.close();
socketserver.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}