遇到了麻烦,请大侠帮忙,不胜感激..
我的本意是:编写socket和client,使两个程序能对话,发送BYE结束对话....以下是源代码,请高手帮忙改改
//package EchoServer;
import java.io.*;
import java.net.*;public class EchoServer {
public static void main(String[] args) {
try {
// establish server socket
ServerSocket s = new ServerSocket(8189);
System.out.println("waiting for client connection....");
// wait for client connection
Socket incoming = s.accept();
System.out.println("a client connection....");
BufferedReader in = new BufferedReader(new InputStreamReader(
incoming.getInputStream()));
BufferedReader in2 = new BufferedReader(new InputStreamReader(
System.in));
PrintWriter out = new PrintWriter(incoming.getOutputStream(), true ); boolean done = false;
while (!done) {
String line = in.readLine();
String line2 = in2.readLine();
if (line == null)
done = true;
else {
System.out.println(line);
out.println("Client Say:" + line2);
if (line.trim().equals("BYE"))
done = true;
}
}
incoming.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
//*****************************************************************************
//package EchoServer;
import java.io.*;
import java.net.*;public class ClientServer {
public static void main(String[] args) {
try {
Socket s = new Socket("1db3e1b9c65e4a4",8189);
BufferedReader in = new BufferedReader(new InputStreamReader(
s.getInputStream()));
BufferedReader in2 = new BufferedReader(new InputStreamReader(
System.in));
PrintWriter out = new PrintWriter(s.getOutputStream(), true );
boolean done = false;
while (!done) {
String line = in.readLine();
String line2 = in2.readLine();
if (line == null)
done = true;
else {
System.out.println(line);
out.println("Server Say:"+line2); if (line.trim().equals("BYE"))
done = true;
}
}
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
我的本意是:编写socket和client,使两个程序能对话,发送BYE结束对话....以下是源代码,请高手帮忙改改
//package EchoServer;
import java.io.*;
import java.net.*;public class EchoServer {
public static void main(String[] args) {
try {
// establish server socket
ServerSocket s = new ServerSocket(8189);
System.out.println("waiting for client connection....");
// wait for client connection
Socket incoming = s.accept();
System.out.println("a client connection....");
BufferedReader in = new BufferedReader(new InputStreamReader(
incoming.getInputStream()));
BufferedReader in2 = new BufferedReader(new InputStreamReader(
System.in));
PrintWriter out = new PrintWriter(incoming.getOutputStream(), true ); boolean done = false;
while (!done) {
String line = in.readLine();
String line2 = in2.readLine();
if (line == null)
done = true;
else {
System.out.println(line);
out.println("Client Say:" + line2);
if (line.trim().equals("BYE"))
done = true;
}
}
incoming.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
//*****************************************************************************
//package EchoServer;
import java.io.*;
import java.net.*;public class ClientServer {
public static void main(String[] args) {
try {
Socket s = new Socket("1db3e1b9c65e4a4",8189);
BufferedReader in = new BufferedReader(new InputStreamReader(
s.getInputStream()));
BufferedReader in2 = new BufferedReader(new InputStreamReader(
System.in));
PrintWriter out = new PrintWriter(s.getOutputStream(), true );
boolean done = false;
while (!done) {
String line = in.readLine();
String line2 = in2.readLine();
if (line == null)
done = true;
else {
System.out.println(line);
out.println("Server Say:"+line2); if (line.trim().equals("BYE"))
done = true;
}
}
s.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
String line = in.readLine();
String line2 = in2.readLine();
if (line == null)
done = true;
else {
System.out.println(line);
out.println("Server Say:"+line2);
你的客户端都没有向服务器端发送数据,只是向服务器要数据line = in.readLine();而你服务器端却在等客户端要数据
while (!done) {
String line = in.readLine();
String line2 = in2.readLine();
这样怎能通讯呢?
这个不就是向服务器端发数据吗...
package cn.cupoy.supertalk.server;import java.io.*;
import java.net.*;
import java.util.*;import org.apache.log4j.Logger;import cn.cupoy.supertalk.log.SuperTalkLog;public final class SuperTalkServer {
private static final Logger LOGGER = SuperTalkLog
.getClassLogger(SuperTalkServer.class); private static final int SERVER_BINDPORT = 8888; private boolean isStarted; private ServerSocket serverSocket; private Socket client; private static final Map<String, ServerThread> clients = new HashMap<String, ServerThread>();
private static final SuperTalkServer superTalkServer = new SuperTalkServer();
/**
* the invisible constructor
*/
private SuperTalkServer() {
} /**
* @return ConnectionData instance
*/
public static SuperTalkServer getInstance() {
return superTalkServer;
} public static void main(String[] args) { getInstance().start(); } private void start() { try {
LOGGER.info("1. start the server.");
serverSocket = new ServerSocket(SERVER_BINDPORT);
isStarted = true;
System.out.println("the Server started!");
LOGGER.info("the Server started!"); LOGGER
.info("2. listen to the client and connect to the worked client");
while (isStarted) {
client = serverSocket.accept();
ServerThread st = new ServerThread(client);
new Thread(st).start();
clients.put(client.getLocalAddress().getHostAddress(), st);
}
} catch (BindException e) {
System.out.println("the port is working now please close");
LOGGER.warn(" the port is working now please close ", e);
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} finally {
try {
if (serverSocket != null) {
serverSocket.close();
serverSocket = null;
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
} /**
* ,every user start a thread to due with
* @author cupoyzhang
*
*/
private class ServerThread implements Runnable {
private Socket client; private BufferedOutputStream bos; private BufferedInputStream bis; private boolean isConnected; ServerThread(Socket client) { this.client = client;
try {
bos = new BufferedOutputStream(client.getOutputStream());
bis = new BufferedInputStream(client.getInputStream());
isConnected = true;
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
} public void run() { String strRead = "";
byte[] bf = new byte[1024];
try {
while (isConnected) {
System.out.println("A client has connected!");
System.out.println("total client is : " + clients.size());
int len = bis.read(bf);
strRead = new String(bf, 0, len);
if ("end".equals(strRead)) {
isConnected = false;
clients.remove(this);
System.out.println("A client has exited!");
System.out.println("total client is : "
+ clients.size());
return;
}
String key = client.getInetAddress().getHostAddress();
ServerThread st = clients.get(key);
st.bos.write(("client1 said:"+ key+"\r\n").getBytes());
st.bos.write(strRead.getBytes());
st.bos.flush();
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} finally {
try {
if (bos != null) {
bos.close();
bos = null;
}
} catch (IOException e1) {
LOGGER.error(e1.getMessage(), e1);
;
}
try {
if (bis != null) {
bis.close();
bis = null;
}
} catch (IOException e1) {
LOGGER.error(e1.getMessage(), e1);
}
try {
if (client != null) {
client.close();
client = null;
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
}
}
}2.客户端package cn.cupoy.supertalk.client;import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;import org.apache.log4j.Logger;import cn.cupoy.supertalk.log.SuperTalkLog;/**
* the client of the superTalk
*
* @author cupoyzhang
*
*/
public class SuperTalkClient {
private static final Logger LOGGER = SuperTalkLog
.getClassLogger(SuperTalkClient.class); private Socket clientSocket; private boolean isConnected; private BufferedOutputStream bos; private BufferedInputStream bis; public SuperTalkClient() {
} public SuperTalkClient(Socket clientSocket) {
this.clientSocket = clientSocket;
} public static void main(String[] args) {
new SuperTalkClient().start(); } private void start() { // 1.connect to the superChat server
try {
clientSocket = new Socket(InetAddress.getByName(null), 8888);
bis = new BufferedInputStream(clientSocket.getInputStream());
bos = new BufferedOutputStream(clientSocket.getOutputStream());
} catch (UnknownHostException e) {
System.out.println("can not find the Host,please check your net!");
e.printStackTrace();
} catch (IOException e) {
System.out.println(" ths system is busy now, please try later");
e.printStackTrace();
}
isConnected = true;
System.out
.println("you have connected to the server,please login if you have registered else please register:"); // 2.bulid the inputStream and let users to input
new Thread(new ReadThread()).start(); // 3.read from server
new Thread(new WriteThread()).start();
} /**
*
* @author cupoyzhang
*
*/
private class ReadThread implements Runnable {
public void run() {
String strRead = null;
byte[] buff = new byte[1024];
try {
while (isConnected) {
int len = bis.read(buff);
strRead = new String(buff, 0, len);
System.out.println(strRead + "\r\n");
}
} catch (StringIndexOutOfBoundsException e) {
System.out.println(" the byte array is not big enough");
LOGGER.warn("the byte array is not big enough", e);
} catch (SocketException e) {
System.out.println(" connect error !");
LOGGER.error(e.getMessage(), e);
} catch (IOException e) {
System.out.println(" read IO error");
LOGGER.error(e.getMessage(), e);
}
} } /**
*
* @author cupoyzhang
*
*/
private class WriteThread implements Runnable {
public void run() {
byte[] buff = new byte[1024];
try {
int len;
while ((len = System.in.read(buff)) != -1) {
if (buff[len - 1] == '\n') {
bos.write(buff, 0, len - 1);
bos.flush();
}
}
} catch (IOException e) {
System.out.println(" IO ERROR,please try it later.");
LOGGER.error(e.getMessage(), e);
try {
System.in.close();
if (bos != null) {
bos.close();
}
} catch (IOException e1) {
LOGGER.error(e.getMessage(), e);
}
LOGGER.error(e.getMessage(), e);
}
} }
}
把里面log4j去掉可以试一下
在你的程序中String line2 = in2.readLine();这个是键盘输入的吧,输入后就要先发过去,String line = in.readLine(); 这个放到最后读出来
Serverimport java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class Handle implements Runnable {
private Socket socket;
Handle(Socket socket) {
this.socket = socket;
}
public BufferedReader getReader(Socket socket) throws IOException {
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
return br;
}
public PrintWriter getWriter(Socket socket) throws IOException {
PrintWriter pw = new PrintWriter(socket.getOutputStream(),true);
return pw;
}
public String echo(String s) { return "echo:"+s; }
@Override
public void run() {
try {
System.out.println("New connection acceped "+
socket.getInetAddress()+":"+socket.getPort());
BufferedReader in = getReader(socket);
PrintWriter out = getWriter(socket);
String s;
while((s=in.readLine())!=null) {
out.println(echo(s));
System.out.println(socket.getInetAddress()+": "+s);
if(s.equals("bye"))
break;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(socket!=null)
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}public class Server {
private int port = 8080;
private ServerSocket serverSocket;
Server() {
try {
serverSocket = new ServerSocket(port);
System.out.println("Server start ....");
} catch (IOException e) {
e.printStackTrace();
}
}
public void server() throws Exception {
Socket socket = null;
ExecutorService exec = Executors.newCachedThreadPool();
while(true) {
socket = serverSocket.accept();
exec.execute(new Handle(socket));
}
}
public static void main(String[] args) {
try {
new Server().server();
} catch (Exception e) {
e.printStackTrace();
}
}}Clientimport java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;public class Client {
private String host = "localhost";
private int port = 8080;
private Socket socket = null;
Client() {
try {
socket = new Socket(host,port);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public BufferedReader getReader(Socket socket) throws IOException {
BufferedReader br = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
return br;
}
public PrintWriter getWriter(Socket socket) throws IOException {
PrintWriter pw = new PrintWriter(socket.getOutputStream(),true);
return pw;
}
public void talk() {
try {
BufferedReader localReader = new BufferedReader(
new InputStreamReader(System.in));
BufferedReader in = getReader(socket);
PrintWriter out = getWriter(socket);
String s;
while((s=localReader.readLine())!=null) {
out.println(s);
System.out.println(in.readLine());
if(s.equals("bye"))
break;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(socket!=null)
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Client().talk();
}}