用java中socket可以把客户端代码和服务器代码写在一起吗

用java中socket可以把客户端代码和服务器代码写在一起吗,第1张

so

easy

给你代码和解释

//根据参数来决定调用运行服务器方法还是客户端方法。

public

static

void

main(String

args[]){

//调用服务器方法

if(args[0]compareTo("-s“)==0)

{

//第二个参数是端口号

port

=

(int)FloatparseFloat(args[1]);

sever();

}

//调用客户端

else

if

(args[0]compareTo("-c")==0)

{

IP

=

args[1];

port

=

=

(int)FloatparseFloat(args[2]);

client();

}

}

原理是这样,

你可以把它设置在按钮上监听

就是

定义一个参数

然后用if

else

懂了吧

还有楼下的不能盗我劳动果实。

这样:

打开eclipse,点击file --> new --> java project会弹出一窗口,project name 文本框里填上 test,---> 点击finsh -->然后点击左边刚建立的test---->new ---> class --->会弹出一个窗口--->name文本框里填上: ChatServer --->> finsh --->然后会生成一个类,你把右边对话框里刚生成的public class ChatServer {

}

这些代码删掉,然后把你的那些代码粘贴到那对话框中,然后你将鼠标放在该对话框中右击,--》 Run AS ---->> java application

这样应该没问题了

import javaio;

import javanet;

public class EchoServer {

private int port = 8000;

private ServerSocket serverSocket;

public EchoServer() throws IOException {

serverSocket = new ServerSocket(port);

Systemoutprintln("服务器启动");

}

public String echo(String msg) {

return "echo:" + msg;

}

private PrintWriter getWriter(Socket socket) throws IOException {

OutputStream socketOut = socketgetOutputStream();

return new PrintWriter(socketOut, true);

}

private BufferedReader getReader(Socket socket) throws IOException {

InputStream socketIn = socketgetInputStream();

return new BufferedReader(new InputStreamReader(socketIn));

}

public void service() {

while (true) {

Socket socket = null;

try {

socket = serverSocketaccept();

Systemoutprintln("New connection accepted"

+ socketgetInetAddress() + socketgetPort());

BufferedReader br = getReader(socket);

PrintWriter pw = getWriter(socket);

String msg = null;

while ((msg = brreadLine()) != null) {

//Systemoutprintln(msg);

pwprintln(echo(msg));

if (msgequals("bye"))

break;

}

} catch (IOException e) {

// TODO Auto-generated catch block

eprintStackTrace();

} finally {

if (socket != null)

try {

socketclose();

} catch (IOException e) {

// TODO Auto-generated catch block

eprintStackTrace();

}

}

}

}

public static void main(String[] args) throws IOException {

new EchoServer()service();

}

}

import javaio;

import javanet;

public class EchoClient {

private String host = "localhost";

private int port = 8000;

private Socket socket;

public EchoClient() throws IOException {

socket = new Socket(host, port);

}

public static void main(String[] args) throws IOException {

new EchoClient()talk();

}

private PrintWriter getWriter(Socket socket) throws IOException {

OutputStream socketOut = socketgetOutputStream();

return new PrintWriter(socketOut, true);

}

private BufferedReader getReader(Socket socket) throws IOException {

InputStream socketIn = socketgetInputStream();

return new BufferedReader(new InputStreamReader(socketIn));

}

public void talk() throws IOException {

try {

PrintWriter pw = getWriter(socket);

BufferedReader br = getReader(socket);

//Systemoutprintln(brreadLine());

//获得客户端控制台的输入

BufferedReader localReader = new BufferedReader(

new InputStreamReader(Systemin));

String msg = null;

while ((msg = localReaderreadLine()) != null) {

pwprintln(msg);

Systemoutprintln(brreadLine());

}

//Systemoutprintln("hello");

} catch (IOException e) {

eprintStackTrace();

} finally {

try {

socketclose();

} catch (IOException e) {

eprintStackTrace();

}

}

}

}

不知道你要的是不是socket编程,我这个是客户端向服务器端写数据,然后服务器端回显给客户端,你适当修改就可以了。

我这里的客户端的数据源是控制台的输入

程序如下:

import javaioBufferedReader;

import javaioFileInputStream;

import javaioInputStreamReader;

public class FileReader

{

public static void main(String[] args) throws Exception

{

BufferedReader reader = new BufferedReader(

new InputStreamReader(new FileInputStream("E:\\test\\Hellojava")));

String info = null;

while((info = readerreadLine()) != null)

{

Systemoutprintln(info);

}

}

}

服务器端(注意要先启动服务器端)

import javaio;

import javanet;

import javaawt;

import javaawtevent;

public class server extends Frame implements ActionListener {

Label label = new Label("交谈内容");

Panel panel = new Panel();

TextField tf = new TextField(10);

TextArea ta = new TextArea();

ServerSocket server;

Socket client;

InputStream in;

OutputStream out;

public server() {

super("服务器");

setSize(250, 250);

paneladd(label);

paneladd(tf);

tfaddActionListener(this);

add("North", panel);

add("Center", ta);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

Systemexit(0);

}

});

show();

try {

server = new ServerSocket(4000);

client = serveraccept();

taappend("客户机是:" + clientgetInetAddress()getHostName() + "\n\n");

in =clientgetInputStream();

out= clientgetOutputStream();

} catch (IOException ioe) {

}

while (true) {

try {

byte[] buf = new byte[256];

inread(buf);

String str = new String(buf);

taappend("客户机说:" + str + "\n\n");

} catch (IOException e) {

}

}

}

public void actionPerformed(ActionEvent e) {

try {

String str = tfgetText();

byte[] buf = strgetBytes();

tfsetText(null);

outwrite(buf);

taappend("我说:" + str + "\n");

} catch (IOException ioe) {

}

}

public static void main(String[] args) {

new server();

}

}

客户端

import javaio;

import javanet;

import javaawt;

import javaawtevent;

public class client extends Frame implements ActionListener {

Label label = new Label("交谈内容");

Panel panel = new Panel();

TextField tf = new TextField(10);

TextArea ta = new TextArea();

Socket client;

InputStream in;

OutputStream out;

public client() {

super("客户机");

setSize(250, 250);

paneladd(label);

paneladd(tf);

tfaddActionListener(this);

add("North", panel);

add("Center", ta);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

Systemexit(0);

}

});

show();

try {

client = new Socket(InetAddressgetLocalHost(), 4000);

taappend("服务器是:" + clientgetInetAddress()getHostName() + "\n\n");

in = clientgetInputStream();

out = clientgetOutputStream();

} catch (IOException ioe) {

}

while (true) {

try {

byte[] buf = new byte[256];

inread(buf);

String str = new String(buf);

taappend("服务器说:" + str + "\n");

} catch (IOException e) {

}

}

}

public void actionPerformed(ActionEvent e) {

try {

String str = tfgetText();

byte[] buf = strgetBytes();

tfsetText(null);

outwrite(buf);

taappend("我说:" + str + "\n");

} catch (IOException iOE) {

}

}

public static void main(String args[]) {

new client();

}

}

这个只能在自己一台电脑上先启动服务器再启动客户端才行,要想一台机子启动服务器端一台机子启动客户端需要把客户端的 client = new Socket(InetAddressgetLocalHost(), 4000);改成 client = new Socket("服务器Ip", 4000);(前提是两台机子连在局域网里面的)

public class SocketTest extends Thread {

private Socket so;

private DataInputStream in;

public static void main(String[] args) {

SocketTest app = new SocketTest();

appstartup();

}

public void startup() {

try {

// 创建服务端socket对象并指定监听端口

ServerSocket ss = new ServerSocket(9999);

Systemoutprintln("listening");

// 等待客户端连接

so = ssaccept();

Systemoutprintln("connected");

// 开始读取数据

start();

} catch (Exception e) {

eprintStackTrace();

}

}

public void run() {

try {

// 创建socket输入流

in = new DataInputStream(sogetInputStream());

while (true) {

try {

// 定义接收缓冲区(64字节)

byte[] buf = new byte[64];

// 将数据读到接收缓冲区中,并返回实际读到的数据长度

int len = inread(buf, 0, 64);

// 长度为-1说明到达输入流末尾,socket已关闭

if (len < 1) {

Systemoutprintln("closed");

break;

}

Systemoutprintln("(" + len + ")");

} catch (Exception e) {

// 读数据异常

eprintStackTrace();

}

}

} catch (Exception e) {

// 监听异常

eprintStackTrace();

}

}

}

DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
网站模板库 » 用java中socket可以把客户端代码和服务器代码写在一起吗

0条评论

发表评论

提供最优质的资源集合

立即查看 了解详情