黑马程序员技术交流社区
标题:
java代码问题
[打印本页]
作者:
鲍霄霄
时间:
2012-7-15 11:25
标题:
java代码问题
package bxx;
import java.awt.image.renderable.RenderableImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.CharBuffer;
import java.util.Scanner;
public class Server {
public static void init() throws IOException {
ServerSocket server=new ServerSocket(8898);
System.out.println("服务器启动...");
while (true) {
Socket s = server.accept();
ServerManager sm = new ServerManager(s);
new Thread(sm).start();
}
}
//main方法
public static void main(String[] args) throws IOException {
Server server=new Server();
server.init();
}
//
class ServerManager implements Readable{
private Socket s=null;
public ServerManager(Socket s){
this.s=s;
}
public void run() throws IOException{
if (s!=null) {
while (true) {
System.out.println("请输入您要发送的信息!");
Scanner b=new Scanner(System.in);
String s1=b.nextLine();
OutputStream out= s.getOutputStream();
out.write(s1.getBytes());
out.flush();
InputStream in=s.getInputStream();
byte[] msg=new byte[1024];
in.read(msg);
System.out.print("客户端说:");
System.out.println(new String(msg).trim());
}
}
}
@Override
public int read(CharBuffer cb) throws IOException {
// TODO Auto-generated method stub
return 0;
}
}
}
作者:
陆强强
时间:
2012-7-15 11:54
本帖最后由 陆强强 于 2012-7-15 11:56 编辑
class Server {
public static void init() throws IOException {
ServerSocket server=new ServerSocket(8898);
System.out.println("服务器启动...");
while (true) {
Socket s = server.accept();
ServerManager sm = new ServerManager(s);
new Thread(sm).start();
}
}
//main方法
public static void main(String[] args) throws IOException {
Server server=new Server();
server.init();
}
//
}//少个大括号
class ServerManager implements Runnable
{//这里是实现Runnable
private Socket s=null;
public ServerManager(Socket s){
this.s=s;
}
public void run()
{//run方法不能抛IOException,所以直接try,加Runtime异常
try
{
if (s!=null) {
while (true) {
System.out.println("请输入您要发送的信息!");
Scanner b=new Scanner(System.in);
String s1=b.nextLine();
OutputStream out= s.getOutputStream();
out.write(s1.getBytes());
out.flush();
InputStream in=s.getInputStream();
byte[] msg=new byte[1024];
in.read(msg);
System.out.print("客户端说:");
System.out.println(new String(msg).trim());
}
}
}
catch (Exception e)
{
throw new RuntimeException();
}
}
public int read(CharBuffer cb) throws IOException {
return 0;
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2