c java socket编程_Java Socket编程之简单的C/S一对一的实现

packagecom.wjy.server;importjava.awt.BorderLayout;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.IOException;importjava.io.InputStreamReader;importjava.net.ServerSocket;importjava.net.Socket;importjavax.swing.JButton;importjavax.swing.JFrame;importjavax.swing.JTextArea;importjavax.swing.JTextField;/*** caution:boot the server first.

*@authorJiyuan Wang

**/

public class TalkServer extends JFrame implementsActionListener{private static JButton send=null;private static JTextField inputText=null;private static JTextArea showText=null;private static ServerSocket serverSocket=null;private static Socket socket=null;private static DataInputStream dataInputStream=null;private static DataOutputStream dataOutputStream=null;publicTalkServer(){

send=new JButton("Send");

send.addActionListener(this);

send.setEnabled(true);

inputText=newJTextField();

showText=newJTextArea();

add(send,BorderLayout.NORTH);

add(inputText, BorderLayout.SOUTH);

add(showText, BorderLayout.CENTER);

setTitle("Server");

setBounds(1000,0,400,400);

setVisible(true);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}public static voidmain(String[] args)

{newTalkServer();try{

serverSocket=new ServerSocket(4170);

socket=serverSocket.accept();

showText.append("Connect successd.\n");

dataInputStream=newDataInputStream(socket.getInputStream());

dataOutputStream=newDataOutputStream(socket.getOutputStream());while (true) {

showText.append("Client said: "+dataInputStream.readUTF()+"\n");

}

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

@Overridepublic voidactionPerformed(ActionEvent e) {//TODO Auto-generated method stub

try{

dataOutputStream.writeUTF(inputText.getText());

dataOutputStream.flush();//本人一直把这个程序调试不通,最后发现没加这句话导致服务端显示不了客户端的输入。

showText.append("I said: "+inputText.getText()+"\n");

}catch(IOException e1) {//TODO Auto-generated catch block

e1.printStackTrace();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值